我有一个包含数千个 .txt 文件的文件夹。我想根据以下模型将它们组合在一个大的 .csv 中:
我发现一个 R 脚本应该可以完成这项工作 ( https://gist.github.com/benmarwick/9265414 ),但它显示了这个错误。
Error in read.table(file = file, header = header, sep = sep, quote = quote, : duplicate 'row.names' are not allowed
我不明白我的错误是什么。
没关系,我很确定没有 R 也有办法做到这一点。如果您知道一个非常优雅和简单的方法,我们将不胜感激(并且对像我这样的很多人有用)
PRECISION :文本文件是法语的,所以不是 ASCII。这是一个示例:https://www.dropbox.com/s/rj4df94hqisod5z/Texts.zip?dl=0
最佳答案
以下 python 脚本对我有用(其中 path_of_directory
替换为文件所在目录的路径,output_file.csv
是文件的路径想要创建/覆盖):
#! /usr/bin/python
import os
import csv
dirpath = 'path_of_directory'
output = 'output_file.csv'
with open(output, 'w') as outfile:
csvout = csv.writer(outfile)
csvout.writerow(['FileName', 'Content'])
files = os.listdir(dirpath)
for filename in files:
with open(dirpath + '/' + filename) as afile:
csvout.writerow([filename, afile.read()])
afile.close()
outfile.close()
请注意,这假定目录中的所有内容都是一个文件。
关于python - 将一个文本文件文件夹合并为一个 CSV,每个内容都在一个单元格中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41913147/