簡體   English   中英

如何在python中添加和合並txt文件?

[英]How to prepend and merge txt files in python?

我正在嘗試使用 Python 合並並在每個 txt 文件前添加一個新行。 所以目標是將所有200個文本文件合並成一個文本文件和一個新行TEXT,將所有200個文件作為文本文件的第一行數據。 我應該預先添加然后合並以使生活更輕松嗎?

我嘗試將新行合並並添加到現有的 txt 文件中,但是當我打開結果文件時,它刪除了文件中的所有內容並添加了一個新行TEXT, . 無論如何我可以解決這個問題嗎?

import glob

read_files = glob.glob("*.txt")

with open("result.txt", "wb") as outfile:
    for f in read_files:

        with open(f, "r") as infile:
            outfile.write(infile.read())

            with open(f,"w+") as infile:
                infile.write("TEXT,"+infile.read())
                with open(f,"r+") as infile:
                    b=infile.read()
                    print b

Actual Result:
TEXT,

Desired Result TEXT, ……………(JUST RANDOM DATA)

這應該做你想做的......或者非常接近......

import fileinput
import glob

# Creating a list of filenames 
filenames = glob.glob("C:\\your_path_here\\*.txt")

# Open file3 in write mode 
with open('consolidated.txt', 'a') as outfile: 

    # Iterate through list 
    for names in filenames: 

        # Open each file in read mode 
        with open(names) as infile: 

            # read the data from file
            outfile.write(infile.read()) 
            outfile.write('\n\n' + 'TEXT' + '\n\n')

文本文件中的最終結果:

FName,LName,Address
Jim,Bentz,34 Holloway La.
George,Hororitz,76 Ridge Dr.
Eric,Schimtz,11 Main St.

TEXT

FName,LName,Address
Jim,Bentz,34 Holloway La.
George,Hororitz,76 Ridge Dr.
Eric,Schimtz,11 Main St.

TEXT

FName,LName,Address
Jim,Bentz,34 Holloway La.
George,Hororitz,76 Ridge Dr.
Eric,Schimtz,11 Main St.

TEXT

FName,LName,Address
Jim,Bentz,34 Holloway La.
George,Hororitz,76 Ridge Dr.
Eric,Schimtz,11 Main St.

TEXT

FName,LName,Address
Jim,Bentz,34 Holloway La.
George,Hororitz,76 Ridge Dr.
Eric,Schimtz,11 Main St.

TEXT

有一些事情需要注意這些事情。

寫入文件的第一步是使用內置的 Python 命令“open”創建文件對象。

要創建和寫入新文件,請使用 open with "w" 選項。 “w”選項將刪除文件中任何先前存在的數據並將(新內容)寫入文件。 “a”選項將附加到文件,而不是寫入(和覆蓋)到文件。 “r”選項用於讀取文件。 有關更多信息,請參閱下面的鏈接。

https://www.tutorialsteacher.com/python/python-read-write-file

暫無
暫無

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

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