2017-10-28 540 views
0

這可能是重複的,但我無法在任何地方找到我的答案。刪除python中文件中特定行的特定字母

我有一個文本文件,我想刪除特定行中的特定字符。

這裏有一個例子:

#textfile.txt 


Hey! 
1234/ 
How are you//? 
9/23r 

我怎樣才能把第二行的斜線?

輸出應該是:

#textfile.txt 


Hey! 
1234 
How are you//? 
9/23r 

我沒有代碼,並就如何做到這一點沒有任何線索。

我在Debian上運行python 2.7.14。

+0

「*我沒有代碼*」,那麼你應該去得到一些。這是一個相當容易實現的事情。你可以從這裏開始:https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files – Gabriel

+0

你想要刪除的「特定行中的特定字符」有什麼特別之處? –

回答

2

你可以閱讀逐行掃描文件並確定要修改的行。然後確定要修改的角色的索引/位置(移除)。 將其替換爲空白並將文本逐行寫入文件。

#opeing the .txt file 
fp = open("data.txt", "r") 
#reading text line by line 
text= fp.readlines() 
#searching for character to remove 
char = text[1][-2] 
#removing the character by replacing it with blank 
text[1] = text[1].replace(char, "") 

#opeing the file in write mode 
fw = open("data.txt", "w") 
#writing lines one by one 
for lines in text: 
    fw.write(lines) 
#closing the file 
fw.close() 
+0

它很好。但是你能解釋一下你使用的索引嗎? –

+1

所以,基本上在你的文件中,每一行最後都有一個下一行('\ n')字符。在Python中,-1是最後一個字符的索引,但是您想要刪除的字符是一個斜線,它在索引爲-2的最後一個字符之前。所以她的文字[1]是第二行,文字[1] [ - 2]是你想刪除的斜線。 –

2

一個簡單的解決方法是在整個文件的讀取,找到你想改變,改變它的路線,並重新寫出來的內容全部

filename = 'textfile.txt' 
original = '1234/' 
replacement = '1234' 
# Open file for reading and read all lines into a list 
with open('textfile.txt') as f: 
    lines = f.readlines() 
# Find the line number (index) of the original string 
index = lines.index(original + '\n') 
# Replace this element of the list 
lines[index] = replacement + '\n' 
# Write out the modified lines to disk 
with open(filename, 'w') as f: 
    f.writelines(lines)