欢迎访问宙启技术站
智能推送

Python文件处理函数及其用法

发布时间:2023-05-23 09:24:54

Python具有很多文件处理函数,这些函数可以帮助我们在Python中完成各种与文件相关的操作。以下是一些常用的Python文件处理函数及其用法:

1. open()

open()函数用于打开文件,并返回一个文件对象。它接受两个参数:文件名和打开模式。常用的打开模式有'r'(只读),'w'(只写),'a'(追加),'x'(写入,如果文件不存在则创建)等。例如:

file = open('myfile.txt', 'r')

2. close()

close()函数用于关闭文件。它不接受参数。例如:

file = open('myfile.txt', 'r')
# do something with the file
file.close()

3. read()

read()函数用于从文件中读取内容。它可以接受一个可选参数n,表示要读取的字节数。如果没有给出n,则读取整个文件。例如:

file = open('myfile.txt', 'r')
content = file.read()    # 读取整个文件
print(content)
file.close()

4. readline()

readline()函数用于逐行读取文件内容。例如:

file = open('myfile.txt', 'r')
line = file.readline()   # 读取一行
while line:
    print(line)
    line = file.readline()
file.close()

5. write()

write()函数用于向文件中写入内容。例如:

file = open('myfile.txt', 'w')
file.write('hello world')
file.close()

6. writelines()

writelines()函数用于向文件中写入多行内容。例如:

file = open('myfile.txt', 'w')
lines = ['line 1
', 'line 2
', 'line 3
']
file.writelines(lines)
file.close()

7. seek()

seek()函数用于移动文件指针到指定位置。它接受两个参数:偏移量和起始位置。常用的起始位置有0(文件开头)、1(当前位置)、2(文件结尾)。例如:

file = open('myfile.txt', 'r')
file.seek(10, 0)         # 将文件指针移动到第10个字节处
content = file.read()
print(content)
file.close()

8. tell()

tell()函数用于获取文件指针的当前位置。它不接受参数。例如:

file = open('myfile.txt', 'r')
file.seek(10, 0)
position = file.tell()   # 获取文件指针的当前位置
print(position)
file.close()

9. with语句

with语句用于自动关闭文件。它会在with语句块执行完毕后自动关闭文件,无需使用close()函数。例如:

with open('myfile.txt', 'r') as file:
    content = file.read()
    print(content)

需要注意的是,在使用with语句时,文件对象需要使用as关键字来进行赋值。

以上是一些常用的Python文件处理函数及其用法,通过使用这些函数,可以帮助我们在Python中完成各种文件处理任务。