为循环中的每个新文件创建一个变量文件名,python

时间:2016-06-07 19:22:08

标签: python file io

我一直试图让这段代码工作几个小时。但它只是不起作用,文件正在创建。但是我从文件中回来的一切都是对我没有意义的东西。

x=raw_input()
p=open(str(x) + ".txt", 'w+')
p.write("Test#1")
print p.read();
p.close()

部分输出是:

w(name, string='') - Return a new hashing object using the named algorithm;
    optionally initialized with a string.
    N(

2 个答案:

答案 0 :(得分:0)

写入文件后,您需要将文件指针移动(搜索)到文件的开头,以便读取工作:

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()

答案 1 :(得分:0)

处理此问题的一种简单方法是在写入文件后关闭文件并重新打开以进行阅读:

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()