专业编程基础技术教程

网站首页 > 基础教程 正文

Python文件读写 python文件读写操作方法

ccvgpt 2024-11-01 11:31:08 基础教程 11 ℃

Python的文件操作主要包括打开、读取、写入和关闭文件。你可以使用open()函数来打开文件,指定模式(如'r'读取,'w'写入)。读取文件可用read()readline()readlines(),写入则用write()writelines()

下面是一些Python文件操作的实战示例,涵盖读取、写入和处理文件的基本操作。

Python文件读写 python文件读写操作方法

1. 写入文件

# 写入数据到文件
with open('example.txt', 'w') as file:
    file.write("Hello, World!\n")
    file.write("This is a file operation example.")

2. 读取文件

# 读取文件内容
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

3. 按行读取文件

# 按行读取文件
with open('example.txt', 'r') as file:
    for line in file:
        print(line.strip())  # strip() 去掉行末的换行符

4. 追加内容到文件

# 追加内容到文件
with open('example.txt', 'a') as file:
    file.write("\nAppending a new line.")

5. 读取所有行到列表

# 将所有行读取到列表
with open('example.txt', 'r') as file:
    lines = file.readlines()
    print(lines)  # 每一行是列表中的一个元素

6. 处理文件异常

# 处理文件操作异常
try:
    with open('non_existent_file.txt', 'r') as file:
        content = file.read()
except FileNotFoundError:
    print("文件未找到,请检查文件名或路径。")



Tags:

最近发表
标签列表