为循环中的每个新文件创建一个变量文件名,python
问题描述:
我一直试图让这段代码工作几个小时。但它不起作用,正在创建文件。但是,我从文件中回来的东西是对我没有意义的东西。为循环中的每个新文件创建一个变量文件名,python
x=raw_input()
p=open(str(x) + ".txt", 'w+')
p.write("Test#1")
print p.read();
p.close()
一些。OUPUTS是:
w(name, string='') - Return a new hashing object using the named algorithm;
optionally initialized with a string.
N(
答
写入文件后,你需要移动(搜索)文件指针到文件的开头,以便读取工作:
x=raw_input()
p=open(str(x) + ".txt", 'w+')
p.write("Test#1")
p.seek(0) # <== Seek to the beginning
print p.read()
p.close()
答
处理这种情况的一个简单的方法是写它,并重新打开它看完后关闭文件:
x=raw_input()
p=open(str(x) + ".txt", 'w+')
p.write("Test#1")
p.close()
p=open(str(x) + ".txt", 'r')
print p.read();
p.close()
您应该关闭并重新打开文件以刷新您的输入缓冲区: – Brian
至少在打开的只写文件上调用'read'是不合法的,如果它是合法的,则需要回头查找在阅读之前开始。 –
@ToddKnarr - 文件是用''w +''模式打开的,这意味着可以书写和阅读。参考:https://docs.python.org/2/library/functions.html#open –