如何修复python不写入文件

时间:2019-07-11 10:58:50

标签: python file-handling

我正在编写一个脚本,用于读取字典并挑选出符合搜索条件的单词。该代码运行良好,但是问题是它没有将任何单词写入文件“哇”或将它们打印出来。字典的来源是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

它创建了“哇”文件,但它为空。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

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

P.S。感谢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