1. 程式人生 > >python操作txt檔案中資料教程[4]-python去掉txt檔案行尾換行

python操作txt檔案中資料教程[4]-python去掉txt檔案行尾換行

python操作txt檔案中資料教程[4]-python去掉txt檔案行尾換行

覺得有用的話,歡迎一起討論相互學習~Follow Me

參考文章
python操作txt檔案中資料教程[1]-使用python讀寫txt檔案
python操作txt檔案中資料教程[2]-python提取txt檔案中的行列元素
python操作txt檔案中資料教程[3]-python讀取資料夾中所有txt檔案並將資料轉為csv檔案

誤區

  • 使用python對txt檔案進行讀取使用的語句是open(filename, 'r')
  • 使用python對txt檔案進行寫入使用的語句是open(fileneme, 'w')
  • 所以如果 要通過python對原始檔案讀取後,直接進行重新寫入到原始檔案 , 即讀到原始檔案中有"\n"或"\r\n" 的地方,然後直接刪除字元這是不現實的。應該是先通過 open(filename, 'r') 讀取原始檔案內容,再使用open(fileneme, 'w') 將刪除了行尾回車符的字串寫入到新的檔案中。 即要做 讀寫分離

例項

  • 對於原始檔案
  • 使用以下語句只是對讀出的內容刪除了行尾的換行符,而不是真正將修改的結果寫入到原始的檔案中。
filename = "./text.txt"
with open(filename, 'r') as f:
    print("open OK")
    for line in f.readlines():
        for a in line:
            # print(a)
            if a == '\n':
                print("This is \\n")
                a = " "
    for line in f.readlines():
        for a in line:
            if a == '\n':
                print("This is \\r\\n")
    for line in f.readlines():
        line = line.replace("\n", " ")
        line = line.strip("\n")

"""open OK
This is \n
This is \n
This is \n
This is \n
This is \n
This is \n
This is \n
This is \n
This is \n
This is \n
This is \n
This is \n
This is \n
This is \n
This is \n
This is \n
"""
  • 但是原始檔案並沒有被修改

正確做法

  • 將檔案中的讀取後,使用寫語句將修改後的內容重新寫入新的檔案中
with open('./text_1.txt', 'w') as f:
    with open('./text.txt', 'r') as fp:
        for line in fp:
            line = str(line).replace("\n", " ")
            f.write(line)

  • It's very nice~!!