我正在尝试使用Python将多个(10-100)大文件(100 1GB 1GB)连接到一个。我知道cat是高效和快速的,但是由于可重复性,我想用Python来实现它,并且把所有的代码都作为python,而不使用shell脚本。
我试过:
path_with_txt_files = os.getcwd()
print("Current working directory is:",os.getcwd())
tempfiles=[f for f in os.listdir(path_with_txt_files) if f.endswith('.txt')]
print(tempfiles)
f = open("Concatenated.txt", "w")
for tempfile in tempfiles:
f.write(tempfile.read())我本想把它连在一起的,但我得到了
异常发生: AttributeError 'str‘对象没有属性'read’
我知道tempfiles是字符串列表,但如何将其转换为文件句柄列表?
发布于 2019-07-31 09:04:30
您需要打开tempfile:
for tempfile in tempfiles:
f.write(open(tempfile, "r").read())发布于 2019-07-31 09:02:17
相反,将您的tempfiles收集为文件对象的生成器。
tempfiles = (open(f) for f in os.listdir(path_with_txt_files) if f.endswith('.txt'))
with open("Concatenated.txt", "w") as f_out:
for tempfile in tempfiles:
f_out.write(tempfile.read())发布于 2019-07-31 09:03:32
让我试着用您的代码向您展示这个问题。您正在尝试调用“读取”文件的名称,而不是文件对象本身。相反,你可以这样做:
path_with_txt_files = os.getcwd()
print("Current working directory is:",os.getcwd())
tempfiles=[f for f in os.listdir(path_with_txt_files) if f.endswith('.txt')]
print(tempfiles)
f = open("Concatenated.txt", "w")
for tempfile in tempfiles:
t = open(tempfile,'r')
f.write(t.read())
t.close()https://stackoverflow.com/questions/57286921
复制相似问题