如何使用 Python 覆盖文件中 2 列列表中的字符串选择行?
How to Overwite a string choosen line in 2 Column list in the file using Python?
如何使用 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"')
谁能帮我解决这个难题??
你可以试试这个:
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"
我认为这应该足以满足您的目的。
with open(filename, 'r+') as f:
content = f.read().replace('"T"', '"S"')
f.seek(0)
f.write(content)
f.truncate()
如何使用 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"')
谁能帮我解决这个难题??
你可以试试这个:
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"
我认为这应该足以满足您的目的。
with open(filename, 'r+') as f:
content = f.read().replace('"T"', '"S"')
f.seek(0)
f.write(content)
f.truncate()