将多个文件连接到一个文件对象中,而无需创建新文件 [英] Concatenate multiple files into a single file object without creating a new file

查看:85
本文介绍了将多个文件连接到一个文件对象中,而无需创建新文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题与 Python连接文本文件

我有一个file_names列表,例如['file1.txt', 'file2.txt', ...].

我想将所有文件打开为单个文件对象,可以逐行读取,但是我不想在此过程中创建新文件.有可能吗?

I would like to open all the files into a single file object that I can read through line by line, but I don't want to create a new file in the process. Is that possible?

with open(file_names, 'r') as file_obj:
   line = file_obj.readline()
   while line:
       ...

推荐答案

使用 fileinput 模块输入> .它从多个文件读取,但看起来字符串好像来自单个文件. (懒行迭代).

Use input from fileinput module. It reads from multiple files but makes it look like the strings are coming from a single file. (Lazy line iteration).

import fileinput

files= ['F:/files/a.txt','F:/files/c.txt','F:/files/c.txt']

allfiles = fileinput.input(files)

for line in allfiles: # this will iterate over lines in all the files
    print(line)

# or read lines like this: allfiles.readline()

如果您需要将所有文本都放在一个地方,请使用StringIO

If you need all the text in one place use StringIO

import io

files= ['F:/files/a.txt','F:/files/c.txt','F:/files/c.txt']


lines = io.StringIO()   #file like object to store all lines

for file_dir in files:
    with open(file_dir, 'r') as file:
        lines.write(file.read())
        lines.write('\n')

lines.seek(0)        # now you can treat this like a file like object
print(lines.read())

这篇关于将多个文件连接到一个文件对象中,而无需创建新文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆