可以使用 pathlib 更加紧凑地 编写 。
>>> import os>>> os.chdir('c:/scratch/folder to process')>>> from pathlib import Path>>> with open('big.csv', 'w') as out_file:... csv_out = csv.writer(out_file)... csv_out.writerow(['FileName', 'Content'])... for fileName in Path('.').glob('*.txt'):... csv_out.writerow([str(fileName),open(str(fileName.absolute())).read().strip()])由该glob产生的项目提供对完整路径名和文件名的访问,因此不需要级联。
编辑:我检查了一个文本文件,发现阻塞处理的字符之一看起来像“
fi”,但实际上这两个字符一起作为一个字符。考虑到此csv可能的实际用途,我建议进行以下处理,该处理将忽略诸如此类的奇怪字符。我删除了结尾,因为我怀疑这会使csv处理更加复杂,并且可能是另一个问题的话题。
import csvfrom pathlib import Pathwith open('big.csv', 'w', encoding='Latin-1') as out_file: csv_out = csv.writer(out_file) csv_out.writerow(['FileName', 'Content']) for fileName in Path('.').glob('*.txt'): lines = [ ] with open(str(fileName.absolute()),'rb') as one_text: for line in one_text.readlines(): lines.append(line.depre(encoding='Latin-1',errors='ignore').strip()) csv_out.writerow([str(fileName),' '.join(lines)])


