我正在写一个口袋妖怪游戏,我想制作文件夹来保存不同类型的口袋妖怪,以及其他类型的信息。我想使用文件夹,因为如果我要保存我的所有我会非常麻烦数据到一个文件中。
是否可以使用Python程序创建文件夹?当我尝试从外部网站导入Pokemon数据时,这将使我更容易和更清洁。
答案 0 :(得分:2)
您可以open
使用a
模式,该模式会以附加模式打开文件,如果不存在则创建文件:
my_file = open('file.txt', 'a')
# Optionally: write stuff to my_file, using my_file.write('stuff')
my_file.close()
答案 1 :(得分:1)
如果您想创建文件夹(或目录),则需要os.mkdir
:
import os
os.mkdir("folder_name")
要一次创建一些深文件夹,请使用os.makedirs
:
os.makedirs("path/to/something")
然后将创建三个文件夹的所有结构。
Tutorialspoint有os.mkdir
个简短版tutorial。
答案 2 :(得分:1)
你可以通过执行以下命令运行你想要的任何命令:
import os
os.popen("mkdir random_name") # This creates a directory called "random_name"
os.popen("touch rando_name.txt") # This creates a file called "random_name"
您可以运行通常在popen内的终端中运行的任何命令。
您可以在UNIX(Linux,macOS)以及Windows操作系统中使用popen()命令。 您可以通过查看python文档了解更多相关信息。 https://docs.python.org/2/library/subprocess.html
答案 3 :(得分:0)
您可以像这样使用with statement
:
with open('some_file_100.txt', 'a') as f:
pass
以上只会创建一个空文件,如果你想写一些东西到你创建的文件,你可以尝试:
with open('some_file_100.txt', 'a') as f:
f.write('some text')
当您使用with statement
时,您不需要显式关闭文件,因为它们会在块结束时自动关闭。