如果您的 print 语句完全按照您想要的方式创建该输出,我强烈建议使用新的 pathlib module(在 Python >= 3.4 中可用)来创建您的文件。它非常适合处理类似路径的对象(Windows 和其他操作系统)。
如果您的文件内容以字符串形式存储在data 中,您可以这样做:
from pathlib import Path
file_path = Path('some_file.txt') # a relative file path - points within current directory
file_path.write_text(data) # overwrites existing file of same name
file_path.write_text(data, mode='a') # appends to an existing file of same name
这里有一个小Path 教程。
为了简化:您可以将任何路径(目录和文件路径对象被视为完全相同)构建为对象,可以是绝对路径对象或相对路径对象。
一些有用的路径的简单显示-例如当前工作目录和用户主目录-如下所示:
from pathlib import Path
# Current directory (relative):
cwd = Path() # or Path('.')
print(cwd)
# Current directory (absolute):
cwd = Path.cwd()
print(cwd)
# User home directory:
home = Path.home()
print(home)
# Something inside the current directory
file_path = Path('some_file.txt') # relative path; or
file_path = Path()/'some_file.txt' # also relative path
file_path = Path().resolve()/Path('some_file.txt') # absolute path
print(file_path)
要向下导航文件树,您可以执行以下操作。请注意,第一个对象 home 是 Path,其余的只是字符串:
file_path = home/'Documents'/'project'/'data.txt' # or
file_path = home.join('Documents', 'project', 'data.txt')
要读取位于某个路径的文件,您可以使用其open 方法而不是open 函数:
with file_path.open() as f:
dostuff(f)
但您也可以直接抓取文本!
contents = file_path.read_text()
content_lines = contents.split('\n')
...直接写文本!
data = '\n'.join(content_lines)
file_path.write_text(data) # overwrites existing file
以这种方式检查它是文件还是目录(并且存在):
file_path.is_dir() # False
file_path.is_file() # True
创建一个新的空文件,不要像这样打开它(默默地替换任何现有文件):
file_path.touch()
要使文件仅在文件不存在的情况下,请使用exist_ok=False:
try:
file_path.touch(exist_ok=False)
except FileExistsError:
# file exists
像这样创建一个新目录(在当前目录下,Path()):
Path().mkdir('new/dir') # get errors if Path()/`new` doesn't exist
Path().mkdir('new/dir', parents=True) # will make Path()/`new` if it doesn't exist
Path().mkdir('new/dir', exist_ok=True) # errors ignored if `dir` already exists
以这种方式获取路径的文件扩展名或文件名:
file_path.suffix # empty string if no extension
file_path.stem # note: works on directories too
将name 用于路径的整个最后一部分(如果存在的话,则使用词干和扩展名):
file_path.name # note: works on directories too
使用with_name 方法重命名文件(该方法返回相同的路径对象但具有新的文件名):
new_path = file_path.with_name('data.txt')
您可以像这样使用iterdir 遍历目录中的所有“东西”:
all_the_things = list(Path().iterdir()) # returns a list of Path objects