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

时间:2017-10-28 19:37:49

标签: python python-2.7 python-2.x

这可能是重复的,但我无法在任何地方找到答案。

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

以下是一个例子:

#textfile.txt


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

如何从第二行删除斜杠?

输出应为:

#textfile.txt


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

我没有代码,也没有关于如何做到这一点的线索。

我在Debian上运行python 2.7.14。

2 个答案:

答案 0 :(得分:2)

一个简单的解决方案是读入整个文件,找到要更改的行,更改它,然后再次写出所有内容:< / p>

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)

答案 1 :(得分: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()