【问题标题】:Using a variable to open a text file in Python使用变量在 Python 中打开文本文件
【发布时间】:2017-01-26 16:11:58
【问题描述】:

是否可以使用变量(例如用户名)打开基于该变量命名的文本文件。例如,在以下程序中,文件名为“Username1”,如果它存在,我希望它向其附加详细信息。在以下情况下,我使用的是实际用户名(username1),但我希望它能够在其中插入用户名(这是一个变量)。

#Open Writer to append to file
with open("username1.txt","a") as membersfile:
    membersfileWriter=csv.writer(membersfile)
    membersfileWriter.writerow([viewedlist])

用户名,在这个程序中作为参数传递给这个特定的函数:

def viewfilmfunction(x,username):

【问题讨论】:

  • username+".txt"

标签: python variables tile


【解决方案1】:
username = "placeholder"
with open('{}.txt'.format(username), 'a') as memberfile:
    ...

【讨论】:

    【解决方案2】:
    username = 'username1' # This can be passed in as your function arg.
    with open("%s.txt" % username,"a") as membersfile:
      membersfileWriter=csv.writer(membersfile)
      membersfileWriter.writerow([viewedlist])
    

    这是你要找的吗?

    【讨论】:

    • 如果你想写,我的意思是根据用户名创建一个全新的文件,它会只是“w”而不是“a”吗? ...我不确定这种语法
    猜你喜欢
    • 2019-12-09
    • 1970-01-01
    • 2014-09-11
    • 2015-06-30
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多