一、Python 文件操作

在 Python 中,文件操作是一项重要的功能。以下是一些常见的文件操作方式:

1.1 打开文件

使用 open() 函数来打开文件。它接受文件名和模式作为参数。模式可以是 ‘r’ (只读)、’w’ (只写,如果文件存在则覆盖,不存在则创建)、’a’ (追加,如果文件存在则在末尾添加,不存在则创建)等。

file = open('example.txt', 'r')
1.2 读取文件

可以使用 read() 方法读取整个文件的内容,或者使用 readline() 方法逐行读取。

content = file.read()  # 读取整个文件内容
line = file.readline()  # 读取一行内容
1.3 写入文件

使用 write() 方法向文件中写入内容。

file = open('example.txt', 'w')
file.write('这是写入的内容')
1.4 关闭文件

使用 close() 方法关闭文件,以释放资源。

file.close()
1.5 异常处理

在文件操作中,为了处理可能出现的异常,通常会将操作放在 try-except 块中。

try:
    file = open('example.txt', 'r')
    # 操作文件
except FileNotFoundError:
    print("文件未找到")
finally:
    file.close()

二、读取以及写入文件

以下是 Python 中读取和写入文本文件的示例代码:

def read_text_file(file_path, encoding_type):
    try:
        with open(file_path, 'r', encoding=encoding_type) as file:
            content = file.read()
            print(content)
    except FileNotFoundError:
        print(f"文件 '{file_path}' 未找到")
def write_text_file(file_path, content, encoding_type):
    try:
        with open(file_path, 'w', encoding=encoding_type) as file:
            file.write(content)
    except IOError:
        print(f"写入文件 '{file_path}' 时出错")
# 调用函数读取文件
read_text_file('E:\\test\\host.txt', 'utf-8')
# 调用函数写入文件
write_text_file('E:\\test\\host2.txt', '这是新写入的内容', 'utf-8')

三、处理csv文件

在 Python 中,可以使用内置的 pandas 库来处理 CSV 文件,pandas 是数据分析中常用的库,处理 CSV 文件非常方便。

首先,如果您还没有安装 pandas 库,可以通过以下命令安装:

pip install pandas

以下是一个使用 pandas 读取 CSV 文件的示例代码:

import pandas as pd

# 读取 CSV 文件
data = pd.read_csv('10-days-of-python/day6/data/test3.csv')

# 打印前几行数据,查看读取结果
print(data.head())

data = {'Name': ['Alice,1', 'Bob', 'Charlie'],
        'Age': [25, 30, 35]}
df = pd.DataFrame(data)

df.to_csv('10-days-of-python/day6/data/test4.csv', index=False)

四、处理json文件

在 Python 中,可以使用内置的 json 模块来处理 JSON 文件。

以下是读取 JSON 文件的示例代码:

import json

def read_json_file(file_path):
    try:
        with open(file_path, 'r') as file:
            data = json.load(file)
            return data
    except FileNotFoundError:
        print(f"文件 '{file_path}' 未找到")
    except json.JSONDecodeError:
        print(f"文件 '{file_path}' 不是有效的 JSON 格式")

def write_json_file(file_path, data):
    try:
        with open(file_path, 'w') as file:
            json.dump(data, file, indent=4)  # indent=4 用于添加缩进,使文件更易读
    except IOError:
        print(f"写入文件 '{file_path}' 时出错")

# 示例数据
data = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

write_json_file('10-days-of-python/day6/data/test5.json', data)
# 调用函数读取 JSON 文件
json_data = read_json_file('10-days-of-python/day6/data/test5.json')
print(json_data)