Python基础(二)

在Python中创建文件

  • 在当前目录或指定目录下创建文件
  • 如果不存在则创建一个文件
  • 创建一个以日期和时间为名称的文件
  • 创建具有权限的文件
创建一个空的文本文件

使用内置函数open()创建文件

 open('file_Path or filename', 'access_mode')
文件模式意义
w创建一个新文件进行写入。如果一个文件已经存在,它首先截断该文件。用于创建内容并将其写入新文件。
x打开文件仅用于独占创建。如果文件已存在,则此操作失败。
a以追加模式打开文件并在文件末尾添加新内容。
b创建二进制文件
t以文本模式创建和打开文件
r只读
使用四种方法验证结果
  1. 如果脚本执行时没有错误或异常
  2. 通过手动检查工作目录来查找新文件
  3. 使用该os.listdir(directory_path)功能列出创建文件前后文件夹中的所有文件
  4. 使用该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')
如果不存在则创建文件

有时,如果给定路径中已存在同名文件,则必须不要创建新文件。默认情况下,当您以写入模式打开文件时,如果存在,它将覆盖它。否则,创建新的。
只有当文件不存在时,我们才能使用以下两种方式创建文件:

  1. 使用os.path.exists(“file_path”) 函数检查文件是否存在。
  2. 在 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 模块获取当前日期和时间,并将其分配给文件名,以创建名称中包含日期和时间的文件。

  1. Python 提供了一个 datetime 模块,它有几个类来访问和操作日期和时间戳值。
  2. 首先,获取当前的日期时间值
  3. 接下来,我们需要将 datetime 格式化为字符串以将其用作文件名。
  4. 最后,将其传递给 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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值