在Python中创建文件
- 在当前目录或指定目录下创建文件
- 如果不存在则创建一个文件
- 创建一个以日期和时间为名称的文件
- 创建具有权限的文件
创建一个空的文本文件
使用内置函数open()
创建文件
open('file_Path or filename', 'access_mode')
文件模式 | 意义 |
---|---|
w | 创建一个新文件进行写入。如果一个文件已经存在,它首先截断该文件。用于创建内容并将其写入新文件。 |
x | 打开文件仅用于独占创建。如果文件已存在,则此操作失败。 |
a | 以追加模式打开文件并在文件末尾添加新内容。 |
b | 创建二进制文件 |
t | 以文本模式创建和打开文件 |
r | 只读 |
使用四种方法验证结果
- 如果脚本执行时没有错误或异常
- 通过手动检查工作目录来查找新文件
- 使用该
os.listdir(directory_path)
功能列出创建文件前后文件夹中的所有文件 - 使用该
os.path.isfile(file_path)
函数验证目录中是否存在新创建的文件
import os
# list files from a working directory
print(os.listdir())
# verify file exist
print(os.path.isfile('sales.txt'))
#print
#['sample.txt', 'sales.txt', 'sales_2.txt']
#True
在特定目录中创建文件
要在特定目录中创建文件,我们需要使用绝对路径打开文件。绝对路径包含我们需要使用的文件或目录的完整路径。
它包括定位文件所需的完整目录列表。例如,/user/Pynative/data/sales.txt是发现sales.txt. 查找文件所需的所有信息都包含在路径字符串中。
# create a text file for writing
with open(r'E:\pynative\reports\profit.txt', 'w') as fp:
fp.write('This is first line')
pass
使用自动关闭文件with的语句 可以确保释放与文件相关的所有资源。
如果两个变量中有目录路径和文件名,请使用该os.path.join()函数构造完整路径。该函数接受目录路径和文件名作为参数,并构造一个绝对路径来创建文件。
import os
# Specify the directory path
path = r'E:\pynative\account'
file_name = 'revenue.txt'
# Creating a file at specified folder
# join directory and file path
with open(os.path.join(path, file_name), 'w') as fp:
# uncomment below line if you want to create an empty file
fp.write('This is a new line')
如果不存在则创建文件
有时,如果给定路径中已存在同名文件,则必须不要创建新文件。默认情况下,当您以写入模式打开文件时,如果存在,它将覆盖它。否则,创建新的。
只有当文件不存在时,我们才能使用以下两种方式创建文件:
- 使用os.path.exists(“file_path”) 函数检查文件是否存在。
- 在 open() 函数和 异常处理中使用访问模式 x 。
# example1
import os
file_path = r'E:\pynative\account\profit.txt'
if os.path.exists(file_path):
print('file already exists')
else:
# create a file
with open(file_path, 'w') as fp:
# uncomment if you want empty file
fp.write('This is first line')
访问模式x打开一个文件进行独占创建。如果文件已存在,则此操作失败并显示FileExistsError. 使用 try-except 块来处理这个错误。
#example2
try:
file_path = r'E:\pynative\account\profit.txt'
# create file
with open(file_path, 'x') as fp:
pass
except:
print('File already exists')
使用日期时间创建文件
使用datetime 模块获取当前日期和时间,并将其分配给文件名,以创建名称中包含日期和时间的文件。
- Python 提供了一个 datetime 模块,它有几个类来访问和操作日期和时间戳值。
- 首先,获取当前的日期时间值
- 接下来,我们需要将 datetime 格式化为字符串以将其用作文件名。
- 最后,将其传递给 open() 函数以创建文件
from datetime import datetime
# get current date and time
x = datetime.now()
# create a file with date as a name day-month-year
file_name = x.strftime('%d-%m-%Y.txt')
with open(file_name, 'w') as fp:
print('created', file_name)
# with name as day-month-year-hours-minutes-seconds
file_name_2 = x.strftime('%d-%m-%Y-%H-%M-%S.txt')
with open(file_name_2, 'w') as fp:
print('created', file_name_2)
# at specified directory
file_name_3 = r"E:\demos\files_demos\account\\" + x.strftime('%d-%m-%Y-%H-%M-%S.txt')
with open(file_name_3, 'w') as fp:
print('created', file_name_3)
created 29-06-2021.txt
created 29-06-2021-14-57-24.txt
created E:\demos\files_demos\account\\29-06-2021-14-57-24.txt