从 python 中文件的特定行中删除特定字母

Remove a specific letter from a specific line in a file in python

这可能是重复的,但我找不到我的答案。

我有一个文本文件,我想从特定行中删除特定字符。

这是一个例子:

#textfile.txt


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

如何去掉第二行的斜线?

输出应该是:

#textfile.txt


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

我没有代码,也不知道如何执行此操作。

我 运行 python Debian 上的 2.7.14。

一个简单的解决方案是读入整个文件,找到你想改变的行,改变它,然后写出all 的内容再次:

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)

您可以逐行读取文件并确定要修改的行。然后确定要修改(删除)的字符的 index/location。 将其替换为空白并将文本逐行写入文件。

#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()