首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python连接多个已知扩展名为'str‘对象的大型文件,没有属性'read’

Python连接多个已知扩展名为'str‘对象的大型文件,没有属性'read’
EN

Stack Overflow用户
提问于 2019-07-31 08:58:42
回答 3查看 91关注 0票数 0

我正在尝试使用Python将多个(10-100)大文件(100 1GB 1GB)连接到一个。我知道cat是高效和快速的,但是由于可重复性,我想用Python来实现它,并且把所有的代码都作为python,而不使用shell脚本。

我试过:

代码语言:javascript
复制
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是字符串列表,但如何将其转换为文件句柄列表?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-07-31 09:04:30

您需要打开tempfile:

代码语言:javascript
复制
for tempfile in tempfiles:
  f.write(open(tempfile, "r").read())
票数 2
EN

Stack Overflow用户

发布于 2019-07-31 09:02:17

相反,将您的tempfiles收集为文件对象的生成器。

代码语言:javascript
复制
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())
票数 2
EN

Stack Overflow用户

发布于 2019-07-31 09:03:32

让我试着用您的代码向您展示这个问题。您正在尝试调用“读取”文件的名称,而不是文件对象本身。相反,你可以这样做:

代码语言:javascript
复制
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()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57286921

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档