.write() 不向输出文件写入任何内容 python
.write() not writing anything to ouput file python
所以我试图打开目录中的一堆文件,从这些文件中删除一些单词并将输出写入同一目录中的文件。尝试写入输出文件时遇到问题。没有任何内容写入文件。任何试图解决这个问题的帮助将不胜感激!这是我的代码:
path = 'C:/Users/User/Desktop/mini_mouse'
output = 'C:/Users/User/Desktop/filter_mini_mouse/mouse'
for root, dir, files in os.walk(path):
for file in files:
#print(os.getcwd())
#print(file)
os.chdir(path)
#print(os.getcwd())
with open(file, 'r') as f, open('NLTK-stop-word-list', 'r') as f2:
#x = ''
mouse_file = f.read().split() # reads file and splits it into a list
stopwords = f2.read().split()
x = (' '.join(i for i in mouse_file if i.lower() not in (x.lower() for x in stopwords)))
#print(x)
with open(output, 'w') as output_file:
output_file.write(x)
每次使用循环中的 'w'
模式打开文件时,您都在擦除文件的内容。因此,按照您的代码的方式,如果您的最后一次循环迭代产生空结果,您将不会在文件中看到任何内容。
将模式更改为 'w+'
或 'a'
:
with open(output, 'w+') as output_file:
mode can be 'r' when the file will only be read, 'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending;
所以我试图打开目录中的一堆文件,从这些文件中删除一些单词并将输出写入同一目录中的文件。尝试写入输出文件时遇到问题。没有任何内容写入文件。任何试图解决这个问题的帮助将不胜感激!这是我的代码:
path = 'C:/Users/User/Desktop/mini_mouse'
output = 'C:/Users/User/Desktop/filter_mini_mouse/mouse'
for root, dir, files in os.walk(path):
for file in files:
#print(os.getcwd())
#print(file)
os.chdir(path)
#print(os.getcwd())
with open(file, 'r') as f, open('NLTK-stop-word-list', 'r') as f2:
#x = ''
mouse_file = f.read().split() # reads file and splits it into a list
stopwords = f2.read().split()
x = (' '.join(i for i in mouse_file if i.lower() not in (x.lower() for x in stopwords)))
#print(x)
with open(output, 'w') as output_file:
output_file.write(x)
每次使用循环中的 'w'
模式打开文件时,您都在擦除文件的内容。因此,按照您的代码的方式,如果您的最后一次循环迭代产生空结果,您将不会在文件中看到任何内容。
将模式更改为 'w+'
或 'a'
:
with open(output, 'w+') as output_file:
mode can be 'r' when the file will only be read, 'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending;