这是一个逐个文件而不是逐行编写的解决方案:
for root, dirs, files in os.walk(input_location): for name in files: file_path = os.path.join(root, name) # joins the new path of the file to the current file in order to access the file filestring = '' with open(file_path, 'r') as f: # open the file for line in f: # read file line by line x = remove_stop_words(line,stopwords) filestring+=x filestring+='\n' #Create new line new_file_path = os.path.join(output_location, name) + '_filtered' # creates a new file of the file that is currenlty being filtered of stopwords with open(new_file_path, 'a') as output_file: # opens output file output_file.write(filestring) # writes the newly filtered text to the new output file