Python 写入一个文件赢得';行不通
即使是最基本的代码,我的.txt文件也是空的,我不明白为什么。我正在Python 写入一个文件赢得';行不通,python,Python,即使是最基本的代码,我的.txt文件也是空的,我不明白为什么。我正在python3中运行此子例程,以从用户那里收集信息。当我在记事本和N++中打开.txt文件时,我得到一个空文件 这是我的密码: def Setup(): fw = open('AutoLoader.txt', 'a') x = True while x == True: print("Enter new location to enter") new_entry = s
python3
中运行此子例程,以从用户那里收集信息。当我在记事本和N++中打开.txt文件时,我得到一个空文件
这是我的密码:
def Setup():
fw = open('AutoLoader.txt', 'a')
x = True
while x == True:
print("Enter new location to enter")
new_entry = str(input('Start with \'web\' if it\'s a web page\n'))
fw.write(new_entry)
y = input('New Data? Y/N\n')
if y == 'N' or y == 'n':
fw.close
break
fw.close
Start()
尝试用fw.close()替换fw.close()它在python 3.4上运行
def Setup():
fw = open('AutoLoader3.4.txt', 'a+')
x = True
while x == True:
print("Enter new location to enter")
new_entry = str(input('Start with \'web\' if it\'s a web page\n'))
fw.write(new_entry)
y = input('New Data? Y/N\n')
if y == 'N' or y == 'n':
fw.close()
break
fw.close()
Setup()
由于不知道
Start()
的作用,在回答中必须忽略它,到目前为止
我自己不想费心关闭文件,但让with
语句正确地完成这项工作
以下脚本至少可以工作:
#!/usr/bin/env python3
def Setup():
with open('AutoLoader.txt', 'a') as fw:
while True:
print("Enter new location to enter")
new_entry = str(input("Start with 'web' if it's a web page\n"))
fw.write(new_entry + "\n")
y = input('New Data? Y/N\n')
if y in ['N', 'n']:
break
#Start()
Setup()
见:
另外请注意,启动时可能会自动创建一个缺失的AutoLoader.txt。不是您的问题,但是
fw.close
不会关闭您的文件fw.close()
做什么。Start()
做什么?问题可能是close
,具体取决于运行方式。由于文件未正确关闭,因此当Ash在编辑器中打开文件时,数据可能在缓冲区中。另一句话,您可以对字符串使用双引号,因此不需要对单引号使用转义字符<代码>“如果是网页,则以“web”开头”。只是看起来更干净了一点。@1Up这很可能是因为垃圾收集器在退出解释器时正确地销毁了fw
。当相关代码仍在运行时可能不会发生的某些情况。。。
nico@ometeotl:~/temp$ ./test_script3.py
Enter new location to enter
Start with 'web' if it's a web page
First user's entry
New Data? Y/N
N
nico@ometeotl:~/temp$ ./test_script3.py
Enter new location to enter
Start with 'web' if it's a web page
Another user's entry
New Data? Y/N
N
nico@ometeotl:~/temp$ cat AutoLoader.txt
First user's entry
Another user's entry
nico@ometeotl:~/temp$