🍉CSDN小墨&晓末:https://blog.csdn.net/jd1813346972
个人介绍: 研一|统计学|干货分享
擅长Python、Matlab、R等主流编程软件
累计十余项国家级比赛奖项,参与研究经费10w、40w级横向
【Python操作基础】系列——文件操作,建议收藏!
该篇文章主要涉及保存地址的查询和修改,外部文件(excel、csv、txt)读取。
1 文件保存地址查询
运行程序:
import os
print(os.getcwd())
运行结果:
D:\pythonjupyter
2 修改文件保存地址
运行程序:
import os
os.chdir(r'C:\Users\soloman\clm')
print(os.getcwd())
运行结果:
C:\Users\soloman\clm
3 外部文件读取
3.1 读取Excel格式文件
运行程序:
import openpyxl
import pandas as pd
df=pd.read_excel('C:\\Users\\副本副本.xlsx')#读取数据
df.head(2)##查看前两行
运行结果:
3.2 读取csv格式文件
运行程序:
import csv
# 打开CSV文件
with open('your_file.csv', 'r') as csvfile:
# 创建CSV读取器对象
reader = csv.reader(csvfile)
# 读取所有行
rows = list(reader)
# 打印所有行
for row in rows:
print(row)
3.3 读取txt文件
运行程序:
# 打开文件,'r' 表示只读模式
with open('your_file.txt', 'r', encoding='utf-8') as file:
# 读取文件内容
content = file.read()
# 打印文件内容
print(content)