python 3.4.2 OSERROR:ERRNO 22使用open来写入多个文件

时间:2014-10-30 00:01:38

标签: python

你好我试着写一个关于拥有一个村庄的游戏,让它活着100天但是  在编写保存系统时,我遇到了一个错误,这是我的代码:

filename = input("name of file: ").strip()  
filename = '"'+filename+'"'  
os.system("md "+filename)  
filename = filename.replace('"',"")  
file = open(filename+"\population.txt","w")  
file.write(str(population))  
file.close()  
file = open(filename+"\name.txt","w")  
file.write(str(name))  
file.close()  
file = open(filename+"\days.txt","w")  
file.write(str(days))  
file.close()  
file = open(filename+"\food.txt","w")  
file.write(str(food))  
file.close()  
file = open(filename+"\hours.txt","w")  
file.write(str(hours))  
file.close()  
file = open(filename+"\villagerskilled.txt","w")  
file.write(str(villagerskilled))  
file.close()  

人口有效,但当它命名时,它会给我错误

Traceback (most recent call last):  
file 'C:\Users\user\Desktop\survivor village.py', line 147 in <module>  
file = open(filename+"\name.txt","w")  
OSError: [Errno 22] Invalid argument: "test\name.txt"  

1 个答案:

答案 0 :(得分:1)

这是因为"\n"是一个新行。试试"\\n"r"\n"这可以解决您的问题。此外,python接受Windows上的路径的正斜杠"/",因此使用它们可能更安全。

了解转义字符here.

此外,命名变量&#34; file&#34;通常是不好的形式。因为file()是python中的built-in function