簡體   English   中英

如何根據python中的特定條件將多個文本文件的內容附加到新的文本文件中?

[英]How can I append the content of multiple text file to a new text files based on specific conditions in python?

我有以以下方式命名的文本文件:

  • 301_1.txt
  • 301_2.txt
  • 301_3.txt

我想創建一個新文件,其中所有文件的內容在“ _”之前具有相同的編號。 在這種情況下,新文件應為301.txt。 在Python中執行此操作的最佳方法是什么?

謝謝

這是我的方法:(希望有幫助:))

首先,我們需要存儲以“ 301”開頭的文件:

import os
files = []
directory = os.fsencode(directory of files)

for file in os.listdir(directory):
    filename = os.fsdecode(file)

    if filename.startswith("301"): 
        files.append(filename)

文件目錄是文件所在的目錄。

現在我們需要從文件中獲取數據:

data = []
for f in files:
    with open(f) as file:
        for i,row in enumerate(file):
          data.append(row)

最后,我們需要編寫“ 301.txt”文件:

with open("301.txt",'w') as newfile:
    for row in data:
        newfile.write(row)

你可能會這樣。

# populated by os.listdir or something
FILES = ['301_1.txt', '301_2.txt', '301_3.txt', '302_1.txt', '302_2.txt']


def concat_files(base='301'):
    with open(base + '.txt', 'a+') as basefile:
        for file in [f for f in FILES if f.startswith(base + '_')]:
            with open(file) as content:
                basefile.write(content.read())


concat_files(base='301')
import glob
import os
pwd=os.getcwd()
os.chdir('path_to_your_directory')
for i in glob.glob('*.txt'):
    new_name=i.split('_')[0]    #fetch the name before '_'
    write_file=open(new_name+'.txt','a')  #open file in append mode
    read_file=open(i)
    lines=read_file.read()
    write_file.write(lines)
    write_file.close()
    read_file.close()      #close the files

os.chdir(pwd)            

glob.glob('*.txt')將返回當前目錄中所有擴展名為.txt文件的列表。 首先,將當前目錄存儲在pwd中 ,然后使用os模塊中的os.chdir()進入當前目錄,最后,通過os.chdir(pwd)返回到起始目錄。 如果您不想換行符,請改用read_file.read().rstrip()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM