自学内容网 自学内容网

python 目录和文件基本操作

目录操作

获取当前目录:
import os
dir_path = os.getcwd()
print("当前目录:", dir_path)

当前目录: D:\work\pycharm\object

创建目录:
import os

dir_path = os.getcwd()
print("当前目录:", dir_path)

new_dir = os.path.join(dir_path, "test_dir")
if not os.path.exists(new_dir):
    os.makedirs(new_dir)
    print(f"目录 '{new_dir}' 创建成功")
else:
    print(f"目录 '{new_dir}' 已经存在,跳过创建")

目录 'D:\work\pycharm\object\test_dir' 已经存在,跳过创建

文件操作

创建文件:
import os
dir_path = os.getcwd()
print("当前目录:", dir_path)

new_dir = os.path.join(dir_path, "test_dir")
new_file_path = os.path.join(new_dir, "test.txt")
print(new_file_path)
with open(new_file_path, 'w') as f:
    f.write("hello txt")
    f.close()

D:\work\pycharm\object\test_dir\test.txt

批量创建:
import os
import datetime

dir_path = os.getcwd()
print("当前目录:", dir_path)

new_dir = os.path.join(dir_path, "test_dir")

current_year_month = datetime.datetime.now().strftime("%Y-%m")
print("当前年月是:", current_year_month)

""" 当前年月是: 2024-03 """



for i in range(1, 10):
    new_datetime = current_year_month + '-' + str(i)
    new_file_path = os.path.join(new_dir, f"test{new_datetime}.txt")
    with open(new_file_path, 'w') as f:
        f.write("hello")
        f.close()

批量读取:
print(new_dir)
file_path = os.listdir(new_dir)
print(file_path)
for file_name in file_path:
    # 只处理文件结尾是txt的
    if file_name.endswith(".txt"):
        file_path = os.path.join(new_dir, file_name)
        with open(file_path, 'r') as f:
            f_content = f.read()
            print(f"{file_name}的内容是{f_content}")

打开文件:

如果报错编码问题的话,就在open里面加上  encoding='utf-8'

file_path = '/opt/pytest/file/信息笔记.txt'



#打开文件,只读模式

with open(file_path,'r') as file:

#读取文件内容

        file_content = file.read()

        print(file_content)
向文件追加内容:
with open(new_file_path, 'a') as f:
    f.write("追加数据:hello python" + "\n")
with open(new_file_path, 'r') as f:
    f_content = f.read()
    print(f_content)

excel操作

读取文件
# 读取excel表格内容
import pandas as pd
excel_file_path = r'D:\桌面\运维分工表.xlsx'
# 读取 Excel 文件
df = pd.read_excel(excel_file_path, sheet_name='运维分工')

# print(df.head())
print(df)
写入excel文件
# 将数据写入excel
import openpyxl
wb = openpyxl.Workbook()
sheet = wb.active

sheet['A1'] = '姓名'
sheet['B1'] = '年龄'
sheet['A2'] = '张三'
sheet['B2'] = 25
sheet['A3'] = '李四'
sheet['B3'] = 30

# 保存工作簿到文件
wb.save('人员信息描述.xlsx')


原文地址:https://blog.csdn.net/eighters/article/details/136728377

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!