如何使用Python在文件的2列列表中覆盖字符串选择行?

如何使用Python在文件的2列列表中覆盖字符串选择行?,python,file,arraylist,file-handling,writing,Python,File,Arraylist,File Handling,Writing,如何使用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"

如何使用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=[]
#将您的示例csv文件放在这里
文件名='list.txt'
#读取文件文本
def openFile(文件名):
内容=打开(文件名)
lines=content.readlines()
对于行中的行:
list.append(行)
返回内容
def标记(文件名):
标志=打开(选择“w”)
选择=输入(“输入要标记的编号:”)
在列表中选择:
flag.write(选项[1]。替换('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):

输出文件(out.txt):

“示例”、“S”
“简单”,“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):

输出文件(out.txt):

“示例”、“S”

“简单”,“S”我想这就足够了

with open(filename, 'r+') as f:
    content = f.read().replace('"T"', '"S"')
    f.seek(0)
    f.write(content)
    f.truncate()

我想这对你来说已经足够了

with open(filename, 'r+') as f:
    content = f.read().replace('"T"', '"S"')
    f.seek(0)
    f.write(content)
    f.truncate()

输出仍然是一样的,因为只有行中的第一列要替换,而不是第二列。您是否希望第二列中的值更改?我的输入和输出与您的原始规格匹配。我的意思是输入文件只能更改,不能生成另一个输出文件,只有list.txt要更改?可以吗?好的,可以显示吗告诉我运行我的代码后您的输出是什么样子的?顺便说一句,文件名不同,如果您想要相同的名称,可以添加重命名“删除/移动”命令输出仍然相同,因为只有要替换的行中的第一列而不是第二列。您是否希望第二列中的值更改?我的输入和输出与您的原始规格匹配。我的意思是输入文件只能更改,不能生成另一个输出文件,只有要更改的list.txt可以吗?好的,可以吗运行我的代码后,是否显示输出结果?顺便说一句,文件名不同,如果需要相同的名称,可以添加重命名“删除/移动”命令