首页 > 解决方案 > 不确定如何将处理后的文本写入具有原始文件名的新目录

问题描述

我可以将单个文件写入不同的目录,但是当我尝试遍历目录中的所有文件时,我不知道如何编写处理过的文件。

我已经查看了将 for 循环与 glob 和 os 模块一起使用的示例,但我无法使其适用于我的特定目的。如果有帮助,我可以包含处理发生的代码。

for filename in glob.glob(os.path.join('*.txt')):

with open(filename,'r', encoding='utf-8', errors='ignore') as file:
    words = file.read()

processedwords = lemmatize_words(words)

file = open(filename, 'w')
file.write(processedwords)

我期待文件写入目录。这是返回一个列表。我需要将词形还原的单词保存为其原始文件名。

   C:\Users\Administrator\Desktop\Python Assignments>python readwrite.py
   Traceback (most recent call last):
   File "readwrite.py", line 88, in <module>
   file.write(processedwords)
   TypeError: write() argument must be str, not list

标签: python

解决方案


让我更正你的代码

for filename in glob.glob(os.path.join('*.txt')):

with open(filename,'r', encoding='utf-8', errors='ignore') as file:
    words = file.read()

processedwords = str(lemmatize_words(words)) #change class of lemmatize_words(words)

file = open(filename, 'w')
file.write(processedwords)

问题是lemmatize_words(words)返回一个非字符串值,因此您必须使用str类将其更改为字符串值。因为processedwords不是字符串类型


推荐阅读