gpt4 book ai didi

python - 更新文本文件python中的单个字段

转载 作者:太空宇宙 更新时间:2023-11-03 21:44:41 25 4
gpt4 key购买 nike

我有这个功能:

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() 函数,因此尝试了它,但它不起作用,我不确定我做错了什么。有什么建议吗?

最佳答案

您应该写入另一个流中的文件,打开文件进行写入。还对 readlines() 方法和“替换”部分进行了一些更正(您应该将结果放入变量 field[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()

关于python - 更新文本文件python中的单个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52582735/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com