python如何读取写入

原创
ithorizon 7个月前 (10-02) 阅读数 33 #Python

Python中的文件读取与写入

Python提供了多种文件读取和写入的方法,使得我们可以在程序中轻松地进行文件操作。

文件读取

Python中常用的文件读取方法有两种,一种是使用内置的open()函数,另一种是使用pandas库进行读取。

使用open()函数读取文件时,我们需要指定文件路径、打开文件的模式(如读取、写入、追加等)以及编码方式(如果需要),以下代码演示了如何使用open()函数读取一个文本文件:

file_path = 'path/to/file.txt'
file_mode = 'r'  # 读取文件
file_encoding = 'utf-8'  # 文件编码方式
with open(file_path, file_mode, encoding=file_encoding) as file:
    content = file.read()  # 读取文件内容
    print(content)  # 打印文件内容

使用pandas库读取文件时,我们需要先导入pandas库,然后使用pandas.read_csv()函数读取CSV文件,或者使用pandas.read_excel()函数读取Excel文件,以下代码演示了如何使用pandas库读取一个CSV文件:

import pandas as pd
file_path = 'path/to/file.csv'
df = pd.read_csv(file_path)  # 读取CSV文件
print(df)  # 打印DataFrame对象

文件写入

Python中常用的文件写入方法也有两种,一种是使用内置的open()函数,另一种是使用pandas库进行写入。

使用open()函数写入文件时,我们需要指定文件路径、打开文件的模式(如读取、写入、追加等)以及编码方式(如果需要),以下代码演示了如何使用open()函数写入一个文本文件:

file_path = 'path/to/file.txt'
file_mode = 'w'  # 写入文件
file_encoding = 'utf-8'  # 文件编码方式
with open(file_path, file_mode, encoding=file_encoding) as file:
    file.write('Hello, world!')  # 写入文件内容

使用pandas库写入文件时,我们可以使用pandas.DataFrame.to_csv()函数将DataFrame对象写入CSV文件,或者使用pandas.DataFrame.to_excel()函数将DataFrame对象写入Excel文件,以下代码演示了如何使用pandas库写入一个CSV文件:

import pandas as pd
df = pd.DataFrame({'column1': [1, 2, 3], 'column2': ['a', 'b', 'c']})  # 创建DataFrame对象
df.to_csv('path/to/file.csv', index=False)  # 写入CSV文件,不写入行索引

就是Python中常用的文件读取与写入方法,根据具体的需求和场景,我们可以选择适合的方法进行操作。



热门