首页 > 知识问答 > python如何读取文件
python如何读取文件
在Python中,有多种方法可以读取文件,以下是一些常见的方法:
1、使用open()
函数打开文件,然后使用read()
、readline()
或readlines()
方法读取文件内容。
with open('文件路径', 'r', encoding='utf-8') as file: content = file.read()print(content)
2、使用open()
函数打开文件,然后逐行读取。
with open('文件路径', 'r', encoding='utf-8') as file: for line in file: print(line.strip())
3、使用pandas
库的read_csv()
、read_excel()
等函数读取表格文件。
import pandas as pddata = pd.read_csv('文件路径')print(data)
4、使用json
库的load()
函数读取JSON文件。
import jsonwith open('文件路径', 'r', encoding='utf-8') as file: data = json.load(file)print(data)
5、使用pickle
库的load()
函数读取pickle文件。
import picklewith open('文件路径', 'rb') as file: data = pickle.load(file)print(data)
就是Python中读取文件的一些常用方法。
上一篇
上一篇