python中预挂起多个文本文件的压缩方法

python中预挂起多个文本文件的压缩方法,python,text,prepend,Python,Text,Prepend,有点傻的问题。我正在尝试将多个文本文件apple、banana、pear插入主文本文件frutsalad.txt。 a如何使其更简洁?还有比我展示的更多的水果 input01 = path_include + 'apple.txt' input02 = path_include + 'banana.txt' input03 = path_include + 'pear.txt' prepend01 = open(input01,'r').read() prepend02 = open(inpu

有点傻的问题。我正在尝试将多个文本文件apple、banana、pear插入主文本文件frutsalad.txt。 a如何使其更简洁?还有比我展示的更多的水果

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中上下文管理器的使用,以及。。。作为…:语句

您可以使用glob将所有内容都包含在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)

请注意,此代码假定文件路径不在路径包含中。如果是,则必须添加一些检查并删除最后一次读取。

应该是这样的:

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文件。

而不是打开每个文件,尝试使用Official Librarray,然后您可以以迭代器方式一起打开多个文件,如您所见的功能:

fileinput.input[files[,inplace[,backup[,bufsize[,mode[,openhook][]]]]


看看为什么没有更简单的方法来实现这一点。也请考虑下面的问题,建议使用临时文件,以免在崩溃中造成数据丢失。似乎有一个问题,你的一个语法文件实际上已经意识到我的问题是不完整的,导致了一个不准确的答案。在追加时,文件已包含不应被覆盖的数据,但由列表内容预先指定fruit@Andreuccio然后你需要在我写循环之前将数据读入内存,然后在循环之后的文件末尾写入数据。没有一种方法可以在不写入现有信息的情况下写入文件的开头。