gpt4 book ai didi

python - 将一个文本文件文件夹合并为一个 CSV,每个内容都在一个单元格中

转载 作者:太空宇宙 更新时间:2023-11-04 07:06:34 25 4
gpt4 key购买 nike

我有一个包含数千个 .txt 文件的文件夹。我想根据以下模型将它们组合在一个大的 .csv 中:

enter image description here

我发现一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com