将多个文件连接到一个文件对象中,而无需创建新文件

编程入门 行业动态 更新时间:2024-10-28 14:21:57
本文介绍了将多个文件连接到一个文件对象中,而无需创建新文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

此问题与 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())

更多推荐

将多个文件连接到一个文件对象中,而无需创建新文件

本文发布于:2023-06-05 21:09:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/527644.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   多个   连接到   象中   新文件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!