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

问题描述 投票:0回答:2

如何使用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"')

任何人都可以帮助我解决这个难题?

python file arraylist file-handling writing
2个回答
1
投票

我认为这足以满足您的目的。

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

1
投票

您可以尝试以下方法:

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"
© www.soinside.com 2019 - 2024. All rights reserved.