1

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

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

这一切都在 Python 中。

谢谢!

4

6 回答 6

9

您可以声明如下值:

# 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()
于 2012-07-26T19:18:45.873 回答
4

如果你有

data=['abc','bcd']

你可以做

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

它将创建文件为 abc.txt

将一些文本写入文件

file.writelines('xyz')

file.close()
于 2012-07-26T19:18:19.387 回答
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")
于 2012-07-26T19:46:49.313 回答
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()
于 2014-11-15T01:34:58.313 回答
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。我的空间也。

于 2012-07-26T20:11:11.837 回答
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()
于 2018-08-08T13:43:25.307 回答