我希望将网络的名称作为输入,然后使用与变量相同的名称保存一个文件。有没有一种方法可以获取一个变量,然后将文件命名为变量名?
例如,假设我将名为facebook的网络保存为字典。我能以某种方式获取变量名并将其用作文件名吗?
这一切都是用Python实现的。
谢谢!
发布于 2012-07-26 19:18:46
您可以声明如下所示的值:
# 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-26 19:18:19
如果你有
data=['abc','bcd']
你可以做到
file = open('{0}.txt'.format(data[0]),"w")
这将创建一个abc.txt格式的文件
将一些文本写入文件
file.writelines('xyz')
file.close()
发布于 2012-07-26 19:46:49
我不理解你,因为你的问题不是很清楚,不管怎样,我会发布两个解决方案
如果您希望将文件名命名为变量的名称
我建议使用下面的代码
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")
https://stackoverflow.com/questions/11676458
复制相似问题