有点愚蠢的问题。我正在尝试将多个文本文件(apple
,banana
,pear
)插入到主文本文件(fruitsalad.txt
)中。如何使它更简洁?(PS有比我所展示的更多的果实!)
input01 = path_include + 'apple.txt'
input02 = path_include + 'banana.txt'
input03 = path_include + 'pear.txt'
prepend01 = open(input01,'r').read()
prepend02 = open(input02,'r').read()
prepend03 = open(input03,'r').read()
open(fruitsalad_filepath, 'r+').write(prepend01+prepend02+prepend03 + open(fruitsalad_filepath).read())
假设您有一些列表
fruit = ['apple.txt', 'banana.txt', 'pear.txt']
您可以打开目标文件,然后一次将每个水果文件的内容写入一个
with open(fruitsalad_filepath, 'w+') as salad:
for item in fruit:
with open(path_include+item) as f:
salad.write(f.read())
这样做意味着您不必将文本保存在中间变量中,这可能会吞噬很多内存。另外,您应该阅读有关Python(with ... as ... :
语句)中上下文管理人员的使用
您可以使用glob
(https://docs.python.org/2/library/glob.html)将所有内容都包含在for
循环中。然后,您可以将所有输入的内容都放在字符串中。另外,我将使用with
,以便您不必担心文件处理程序。
import glob
prepend_text = ""
for input in glob.glob("%s*.txt" % (path_include)):
with open(input, 'r') as f:
prepend_text += f.read()
with open(fruitsalad_filepath, 'r') as f:
prepend_text += f.read()
with open(fruitsalad_filepath, 'w') as f:
f.write(prepend_text)
请注意,此代码假定fruitsalad_filepath
不在path_include
中。如果是这样,则必须添加一些支票(并删除最后的读取)。
应该是这样的:
import codecs
# for example you prepared list of .txt files in folder
# all_files - list of all file names
all_files = []
# content from all files
salad_content = ''
for file_name in all_files:
# open each file and read content
with codecs.open(file_name, encoding='utf-8') as f:
salad_content += f.read()
# write prepared content from all files to final file
with codecs.open(fruitsalad_filepath, 'w', 'utf-8') as f:
f.write(salad_content)
用于在文件夹中查找.txt
文件。您可以使用此方法。
while,而不是打开每个文件,而是尝试使用官方的Libraray fileInput,然后您可以以迭代方式一起打开多文件,因为您可以看到该功能:
fileInput.input([文件[,intplope [,backup [,bufsize [,mode [,openhook]]]]]]]