[英]Trying to delete lines in a text file that contain a specific character
我正在測試下面的代碼,但它沒有做我希望它做的事情。
delete_if = ['#', ' ']
with open('C:\\my_path\\AllDataFinal.txt') as oldfile, open('C:\\my_path\\AllDataFinalFinal.txt', 'w') as newfile:
for line in oldfile:
if not any(del_it in line for del_it in delete_if):
newfile.write(line)
print('DONE!!')
基本上,我想刪除任何包含“#”字符的行(我想刪除的行以“#”字符開頭)。 另外,我想刪除任何/所有完全空白的行。 我可以在旅途中通過閱讀列表中的項目來完成此操作,還是需要多次通過文本文件來清理所有內容? TIA。
這很簡單。 在下面檢查我的代碼:
filePath = "your old file path"
newFilePath = "your new file path"
# we are going to list down which lines start with "#" or just blank
marker = []
with open(filePath, "r") as file:
content = file.readlines() # read all lines and store them into list
for i in range(len(content)): # loop into the list
if content[i][0] == "#" or content[i] == "\n": # check if the line starts with "#" or just blank
marker.append(i) # store the index into marker list
with open(newFilePath, "a") as file:
for i in range(len(content)): # loop into the list
if not i in marker: # if the index is not in marker list, then continue writing into file
file.writelines(content[i]) # writing lines into file
關鍵是,我們需要先閱讀所有的行。 並逐行檢查它是否以#
開頭或只是空白。 如果是,則將其存儲到列表變量中。 之后,我們可以通過檢查該行的索引是否在標記中來繼續寫入新文件。
如果您有問題,請告訴我。
如何使用三元運算符?
#First option: within your for loop
line = "" if "#" in line or not line else line
#Second option: with list comprehension
newFile = ["" if not line or "#" in line else line for line in oldfile]
我不確定三元是否有效,因為如果字符串為空,則應顯示異常,因為“#”不會在空字符串中......怎么樣
#Third option: "Staging your conditions" within your for loop
#First, make sure the string is not empty
if line:
#If it has the "#" char in it, delete it
if "#" in line:
line = ""
#If it is, delete it
else:
line = ""
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.