簡體   English   中英

Python:從文本文件的一行中刪除一個字符串 python

[英]Python : delete a string from a line of a text file python

我是 python 菜鳥。 假設我有一個 FRUITS.txt 文件,其中包含

蘋果 8456./unmatched/sfhogh/weyurg/wiagieuw

芒果 5456./unmatched/swagr/arwe/rwh/EJA/AEH

胡蘿卜 7861468./unmatched/def/aghr/arhe/det/aahe

菠蘿 5674./unmatched/awghhr/wh/wh5q/ja/JAE

我需要從文本文件的所有行中刪除不匹配的單詞。我嘗試了 line.strip 命令,但它會刪除文件中的所有內容。

您必須將行拆分為單個值,然后使用 [-1] 獲取最后一個值。 然后你可以用一個空字符串替換單詞“unmatched”(或任何你想要的)。

with open("fruits.txt", "r") as file:
    lines = file.readlines()

for line in lines:
    value = line.split(" ")[-1].replace("unmatched", "")
    print(value)

讀取文件,進行字符串替換並寫入同一個文件

with open('data.txt', 'r+') as f:  # Opens file for read/write
  s = f.read().replace(r' ./unmatched/', r' ./')
  f.seek(0)      # go back to beginning of file
  f.write(s)     # write new content from beginning (pushes original content forward)
  f.truncate()   # drops everything after current position (dropping original content)

測試

輸入文件:'data.txt'

apple 8456 ./unmatched/sfhogh/weyurg/wiagieuw

mango 5456 ./unmatched/swagr/arwe/rwh/EJA/AEH

carrot 7861468 ./unmatched/def/aghr/arhe/det/aahe

pineapple 5674 ./unmatched/awghhr/wh/wh5q/ja/JAE

Output 文件:'new_data.txt'

apple 8456 ./sfhogh/weyurg/wiagieuw

mango 5456 ./swagr/arwe/rwh/EJA/AEH

carrot 7861468 ./def/aghr/arhe/det/aahe

pineapple 5674 ./awghhr/wh/wh5q/ja/JAE

首先你必須讀入文件的內容:

file = open("fruits.txt", 'r') # opening in read mode
file_contents = file.read()
file.close()

移除 substring“不匹配”的方法有很多種。 一種方法是使用“不匹配”作為分隔符來拆分文件內容字符串,然后將其轉回字符串。

file_contents = "".join(file_contents.split("unmatched")

然后你只需要重寫文件。

file = open("fruits.txt", 'w') # now opening in write mode
file.write( file_contents)
file.close()

暫無
暫無

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

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