如何使用python覆盖文件中的一行?
this is my list in text file
"Sample" , "S"
"Simple" , "T"
"test" , "S"
how to Overwite the second line?
"Simple", "T"
into
"Simple", "S"
then the text file will be change like this:
"Sample" , "S"
"Simple" , "S"
"test" , "S"
这是我使用功能的代码对于流程
list = []
#put your sample csv file here
fileName = 'list.txt'
#reading file text
def openFile(filename):
content = open(filename)
lines = content.readlines()
for line in lines:
list.append(line)
return content
def mark(fileName):
flag = open(pick, "w")
choice = input("Enter number to mark: ")
for choice in list:
flag.write(choice[1].replace('"T"', '"S"')
任何人都可以帮助我解决这个难题?
我认为这足以满足您的目的。
with open(filename, 'r+') as f:
content = f.read().replace('"T"', '"S"')
f.seek(0)
f.write(content)
f.truncate()
您可以尝试以下方法:
list = []
#put your sample csv file here
fileName = 'list.txt'
#reading file text
def openFile(filename):
content = open(filename)
lines = content.readlines()
for line in lines:
list.append(line)
content.close()
return content
def mark(fileName):
flag = open(fileName, "w")
choice = input("Enter number to mark: ")
list[int(choice)] = list[int(choice)].replace('"T"','"S"')
for line in list:
flag.write(line)
cnt = openFile(fileName)
mark(fileName)
输入文件(list.txt):
"Sample" , "S"
"Simple" , "T"
"test" , "S"
输出文件(out.txt):
"Sample" , "S"
"Simple" , "S" <---- this value changed from a T to a S
"test" , "S"