【问题标题】:Update single field in text file python更新文本文件python中的单个字段
【发布时间】:2018-09-30 22:38:40
【问题描述】:

我有这个功能:

def favourites():
name = input("Enter your name as you did when you signed up: ")
new_artist = input("Would you like to edit your favourite artist? y/n ").lower().strip()
if new_artist == 'yes' or new_artist == 'y':
    old_artist = input("Enter the favourite artist you used when signing up: ")
    artist = input("Enter your new favourite artist: ")
    usersFile = open('users.txt', 'r+')
    usersRec = usersFile.readline()
    # reads each line in the file
    while usersRec != "":
        # splits each record into fields 
        field = usersRec.split(',')
        if field[0] == name:
            usersFile.write(field[2].replace(old_artist, artist))
        usersRec = usersFile.readline()
    usersFile.close()

我已读取文本文件中的一行,然后将其拆分为多个字段,我想更新一个字段。搜索并找到了 update() 函数,所以尝试了一下,但它不起作用,我不确定我做错了什么。有什么建议吗?

【问题讨论】:

    标签: python python-3.x file-handling


    【解决方案1】:

    您应该在另一个流中写入文件,打开文件进行写入。还对 readlines() 方法和“替换”部分进行了一些更正(您应该将结果放入变量字段 [2]):

         import io
         import sys
    
    def favourites():
        content=[]
        name = input("Enter your name as you did when you signed up: ")
        new_artist = input("Would you like to edit your favourite artist? y/n 
                      ").lower().strip()
        if new_artist == 'yes' or new_artist == 'y':
           old_artist = input("Enter the favourite artist you used when signing 
                         up: ")
           artist = input("Enter your new favourite artist: ")
    
             with open('users.txt', 'r+') as usersFile:
               usersRec = usersFile.readlines()
               print(usersRec)
    # reads each line in the file
               for ur in usersRec:
    
        # splits each record into fields 
                  field = ur.split(',')
                  if field[0] == name:
                    field[2] = field[2].replace(old_artist, artist)
                    content.append(','.join(field))
                  else: 
                    content.append(','.join(field))
            usersRec = usersFile.readline()
    
         usersFile.close()
    
      writeToFile(content)
    
    
    def writeToFile(content):
       with open('users.txt', 'w+') as usersFile:
          for line in content:
            usersFile.write(line)
       usersFile.close()
    
    if __name__=="__main__":
        favourites()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 2019-10-20
      • 2018-02-15
      • 1970-01-01
      • 2015-01-10
      • 2018-07-13
      相关资源
      最近更新 更多