如何使用代码在 Python 中创建永久文件? - Repl.it
How Do You Make a Permanent File in Python Using Code? - Repl.it
我正在尝试使用代码为每个使用我的程序的新人制作两个文件。到目前为止我有:
import os
playeritems = 'PlayerFiles/PlayerItems'
playergold = 'PlayerFiles/PlayerGold'
file_number = '7'
with open(os.path.join(playeritems, "inventory.%s.txt" % file_number), "w") as f, open(os.path.join(playergold, "gold.%s.txt" % file_number), "w") as g:
#do stuff
with open(os.path.join(playeritems, "inventory.%s.txt" % file_number), "r"):
#Fails to find the file.
但是这段代码运行后,文件不存在了。如何使文件在使用后永久存在?我查看了网站 that briefs you on files,,但没有帮助。感谢您的时间和考虑!
the error occurs on the second with-statement. file inventory.7.txt doesn't exist!
我在这里看到的问题是文件的给定路径中的目录不存在,您正尝试使用 'open' 动态创建它们,但是,这样做是不可能的。
解决这个问题的方法是检查文件路径是否真的存在,如果存在则打开文件,如果不存在则创建目录和完整路径。
对于您的示例,代码如下:
import os
playeritems = str(os.getcwd())+'/PlayerFiles/PlayerItems/'
playergold = str(os.getcwd())+'/PlayerFiles/PlayerGold/'
file_number = '7'
#check if PlayerItem path exist, if not create directories that are needed
if not os.path.exists(os.path.dirname(playeritems)):
try:
os.makedirs(os.path.dirname(playeritems))
print("created PlayerItem path")
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
#check if PlayerGold Path exist, if not create directories that are needed
if not os.path.exists(os.path.dirname(playergold)):
try:
os.makedirs(os.path.dirname(playergold))
print("created PlayerGold Path")
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
with open(os.path.join(playeritems, "inventory.%s.txt" % file_number), "w") as f, open(os.path.join(playergold, "gold.%s.txt" % file_number), "w") as g:
#do stuff
print("inventoryfile and goldfile created!")
with open(os.path.join(playeritems, "inventory.%s.txt" % file_number), "r"):
#do Stuff
print("Reopened playeritem inventory file")
我一定是目录有问题,因为
with open("inventory.%s.txt" % file_number, "w") as f, open("gold.%s.txt" % file_number, "w") as g:
使文件永久化。我实际上并不需要这些文件夹,所以我可以不处理任何目录。
在我的测试中,这肯定是目录的问题。
如果文件的父目录不存在,Python 将拒绝创建该文件:
>>> from pathlib import Path
>>> my_dir = Path('directory_base')
>>> with open(my_dir / 'example.txt', 'w') as f:
>>> f.write('Hi there!')
FileNotFoundError: [Errno 2] No such file or directory: 'directory_base\example.txt'
这很容易通过创建目录来解决。 pathlib.Path
对象有一个名为 mkdir()
的便捷方法可以同时创建任何和所有父目录:
>>> from pathlib import Path
>>> my_dir = Path('directory_base')
>>> my_dir.mkdir(parents=True, exist_ok=True)
>>> with open(my_dir / 'example.txt', 'w') as f:
>>> f.write('Hi there!')
>>> with open(my_dir / 'example.txt') as f:
>>> print(f.read())
'Hi there!'
parents=True
表示应该创建所有父目录,exist_ok
表示如果目录已经存在,Python 不应抛出异常。
如果目录不存在则创建,makedirs
创建所有子目录
import os
playeritems = 'PlayerFiles/PlayerItems'
playergold = 'PlayerFiles/PlayerGold'
#check if directory exists else create new
if not os.path.exists(playeritems):
os.makedirs(playeritems)
if not os.path.exists(playergold):
os.makedirs(playergold)
file_number = '7'
with open(os.path.join(playeritems, "inventory.%s.txt" % file_number), "w") as f, open(os.path.join(playergold, "gold.%s.txt" % file_number), "w") as g:
#do stuff
with open(os.path.join(playeritems, "inventory.%s.txt" % file_number), "r"):
#will find the file
我正在尝试使用代码为每个使用我的程序的新人制作两个文件。到目前为止我有:
import os
playeritems = 'PlayerFiles/PlayerItems'
playergold = 'PlayerFiles/PlayerGold'
file_number = '7'
with open(os.path.join(playeritems, "inventory.%s.txt" % file_number), "w") as f, open(os.path.join(playergold, "gold.%s.txt" % file_number), "w") as g:
#do stuff
with open(os.path.join(playeritems, "inventory.%s.txt" % file_number), "r"):
#Fails to find the file.
但是这段代码运行后,文件不存在了。如何使文件在使用后永久存在?我查看了网站 that briefs you on files,,但没有帮助。感谢您的时间和考虑!
the error occurs on the second with-statement. file inventory.7.txt doesn't exist!
我在这里看到的问题是文件的给定路径中的目录不存在,您正尝试使用 'open' 动态创建它们,但是,这样做是不可能的。
解决这个问题的方法是检查文件路径是否真的存在,如果存在则打开文件,如果不存在则创建目录和完整路径。
对于您的示例,代码如下:
import os
playeritems = str(os.getcwd())+'/PlayerFiles/PlayerItems/'
playergold = str(os.getcwd())+'/PlayerFiles/PlayerGold/'
file_number = '7'
#check if PlayerItem path exist, if not create directories that are needed
if not os.path.exists(os.path.dirname(playeritems)):
try:
os.makedirs(os.path.dirname(playeritems))
print("created PlayerItem path")
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
#check if PlayerGold Path exist, if not create directories that are needed
if not os.path.exists(os.path.dirname(playergold)):
try:
os.makedirs(os.path.dirname(playergold))
print("created PlayerGold Path")
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
with open(os.path.join(playeritems, "inventory.%s.txt" % file_number), "w") as f, open(os.path.join(playergold, "gold.%s.txt" % file_number), "w") as g:
#do stuff
print("inventoryfile and goldfile created!")
with open(os.path.join(playeritems, "inventory.%s.txt" % file_number), "r"):
#do Stuff
print("Reopened playeritem inventory file")
我一定是目录有问题,因为
with open("inventory.%s.txt" % file_number, "w") as f, open("gold.%s.txt" % file_number, "w") as g:
使文件永久化。我实际上并不需要这些文件夹,所以我可以不处理任何目录。
在我的测试中,这肯定是目录的问题。
如果文件的父目录不存在,Python 将拒绝创建该文件:
>>> from pathlib import Path
>>> my_dir = Path('directory_base')
>>> with open(my_dir / 'example.txt', 'w') as f:
>>> f.write('Hi there!')
FileNotFoundError: [Errno 2] No such file or directory: 'directory_base\example.txt'
这很容易通过创建目录来解决。 pathlib.Path
对象有一个名为 mkdir()
的便捷方法可以同时创建任何和所有父目录:
>>> from pathlib import Path
>>> my_dir = Path('directory_base')
>>> my_dir.mkdir(parents=True, exist_ok=True)
>>> with open(my_dir / 'example.txt', 'w') as f:
>>> f.write('Hi there!')
>>> with open(my_dir / 'example.txt') as f:
>>> print(f.read())
'Hi there!'
parents=True
表示应该创建所有父目录,exist_ok
表示如果目录已经存在,Python 不应抛出异常。
如果目录不存在则创建,makedirs
创建所有子目录
import os
playeritems = 'PlayerFiles/PlayerItems'
playergold = 'PlayerFiles/PlayerGold'
#check if directory exists else create new
if not os.path.exists(playeritems):
os.makedirs(playeritems)
if not os.path.exists(playergold):
os.makedirs(playergold)
file_number = '7'
with open(os.path.join(playeritems, "inventory.%s.txt" % file_number), "w") as f, open(os.path.join(playergold, "gold.%s.txt" % file_number), "w") as g:
#do stuff
with open(os.path.join(playeritems, "inventory.%s.txt" % file_number), "r"):
#will find the file