Python语言文件操作-10天学会Python

喜欢花科技君 2025-03-07 02:53:51

在Python编程中,文件操作函数允许你读取和写入文件。

打开文件

使用open()函数打开文件。该函数返回一个文件对象,可以用来读取或写入文件。

语法:file_object = open(file_path, mode)

常用模式(mode):

'r':读取模式(默认)。'w':写入模式(会覆盖文件)。'a':追加模式。'b':二进制模式(如'rb','wb')。't':文本模式(默认)。# 打开一个文本文件用于读取file = open('example.txt', 'r')读取文件

读取整个文件内容

使用read()方法读取整个文件内容。

file = open('example.txt', 'r')content = file.read()print(content)file.close()

逐行读取文件

使用readline()方法逐行读取文件内容。使用readlines()方法逐行读取文件内容。# 读取一行line = file.readline()print(line)# 读取所有行lines = file.readlines()for line in lines: print(line)

使用with语句读取文件

使用with语句可以自动管理文件的打开和关闭,避免手动调用close()。

with open('example.txt', 'r') as file: for line in file: print(line)写入文件

写入字符串到文件

使用write()方法将字符串写入文件。

with open('output.txt', 'w') as file: file.write("Hello, World!\n") file.write("This is a new line.")

追加内容到文件

使用'a'模式以追加方式打开文件。

with open('output.txt', 'a') as file: file.write("\nAppending a new line.")

使用with语句管理文件

with语句可以确保文件在使用后正确关闭,即使在发生异常的情况下也是如此。

try: with open('example.txt', 'r') as file: data = file.read() print(data)except FileNotFoundError: print("文件未找到")

Python语言文件操作

0 阅读:0

喜欢花科技君

简介:感谢大家的关注