如何在Python中使用变量名称命名文件?

时间:2012-07-26 19:14:29

标签: python variables io

我想将网络名称作为输入,然后我希望使用与变量相同的名称保存文件。有没有办法获取变量,然后将变量名称命名为文件?

例如,假设我将名为facebook的网络保存为字典。我可以以某种方式获取该变量名称并将其用作文件名吗?

这一切都在Python中。

谢谢!

6 个答案:

答案 0 :(得分:8)

您可以声明如下值:

# Let's create a file and write it to disk.
filename = "facebook.txt"

# Create a file object:
# in "write" mode
FILE = open(filename,"w")

# Write all the lines at once:
FILE.writelines("Some content goes here")

# Close
FILE.close()

答案 1 :(得分:4)

如果你有

data=['abc','bcd']

你可以做到

file = open('{0}.txt'.format(data[0]),"w")

将创建文件为     的abc.txt

将一些文字写入文件

file.writelines('xyz')

file.close()

答案 2 :(得分:1)

我不理解你,导致你的问题不是很清楚,反正我会发布两个解决方案

如果您希望将文件名命名为变量名称

我建议使用此代码

for i in locals():
  if 'variable name' is i:IObject = open(i+".txt",'w')#i've added .txt extension in case you want it text file 
IObject.write("Hello i'm file name.named with the same name of variable")

或其他

name_of_file = raw_input("Enter the name")
IOjbect = open(name_of_file+".txt","w")
IObject.write("Hey There")

答案 3 :(得分:0)

会这样做吗?

n_facebook = {'christian': [22, 34]}
n_myspace = {'christian': [22, 34, 33]}

for network in globals():
    if network.startswith('n_'):
        # here we got a network
        # we save it in a file ending with _network.txt without n_ in beginning
        file(network[2:] + '_network.txt', 'w').write(str(globals()[network]))

此文件将n_facebook保存到facebook_network.txt。还有myspace。

答案 4 :(得分:0)

我正在尝试这种方法而且我遇到了一个非常奇怪的问题,我的项目被保存到一个程序运行的文件中。因此,如果我运行一次该文件,则不会发生任何事情。第二次,将保存运行中的信息。

f = open("results_{0}.txt".format(counter), 'w')
f.write("Agent A vs. Champion\n"
      + "Champion wins = "
      + str(winsA1)
      + " Agent A wins = "
      + str(winsB1))
f.write("\n\nAgent B vs. Champion\n"
      + "Champion wins = "
      + str(winsA2)
      + " Agent B wins = "
      + str(winsB2))
f.write("\n\nRandom vs. Champion\n"
      + "Champion wins = "
      + str(winsA3)
      + " Random wins = "
      + str(winsB3))
f.close()

答案 5 :(得分:0)

这是一种使文件名成为用户输入的简单方法:

#Here the user inputs what the file name will be.
name_of_file = input("Enter what you want the name of the file to be.")

#Then the file is created using the user input.
newfile = open(name_of_file + ".txt","w")

#Then information is written to the file.
newfile.write("It worked!")

#Then the file is closed.
newfile.close()