繁体   English   中英

如何修复python不写入文件

[英]How to fix python not writing to file

我正在编写一个脚本,该脚本读取字典并挑选出符合搜索条件的单词。 该代码运行良好,但是问题是它没有将任何单词写入文件“哇”或将它们打印出来。 该词典的来源是https://github.com/dwyl/english-words/blob/master/words.zip

我尝试将文件的开头更改为“ w +”而不是“ a +”,但没有任何区别。 我检查了是否没有符合条件的单词,但这不是问题。

listExample = []  #creates a list

with open("words.txt") as f:  #opens the "words" text file
    for line in f:
        listExample.append(line)

x = 0
file = open("wow.txt","a+") #opens "wow" so I can save the right words to it

while True:
    if x < 5000: # limits the search because I don't want to wait too long
        if len(listExample[x]) == 11: #this loop iterates through all words
            word = listExample[x]     #if the words is 11 letters long  
            lastLetter = word[10]
            print(x)
            if lastLetter == "t":    #and the last letter is t
                file.write(word)      #it writes the word to the file "wow"
                print("This word is cool!",word) #and prints it
            else:
                print(word) #or it just prints it
        x += 1 #iteration
    else:
        file.close()
        break #breaks after 5000 to keep it short

它创建了“哇”文件,但它是空的。 如何解决此问题?

这样可以解决您的问题。 您以这样一种方式拆分文本,即每个单词的末尾都有一个换行符,也可能有一个空格。 我已经放入.strip()摆脱了任何空格。 另外,我已将lastLetter定义为word[-1]以获取最后一个字母,而不管单词的长度如何。

PS感谢Ocaso Protal建议剥离而不是更换。

listExample = []  #creates a list

with open("words.txt") as f:  #opens the "words" text file
    for line in f:
        listExample.append(line)

x = 0
file = open("wow.txt","a+") #opens "wow" so I can save the right words to it

while True:
    if x < 5000: # limits the search because I don't want to wait too long
        word = listExample[x].strip()
        if len(word) == 11:
            lastLetter = word[-1]
            print(x)
            if lastLetter == "t":    #and the last letter is t
                file.write(word + '\n')      #it writes the word to the file "wow"
                print("This word is cool!",word) #and prints it
            else:
                print(word) #or it just prints it
        x += 1 #iteration
    else:
        print('closing')
        file.close()
        break #breaks after 5000 to keep it short

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM