详解python3文件操作步骤

高洛峰
Release: 2017-03-24 15:36:44
Original
1474 people have browsed it

步骤:打开文件-》操作文件-》关闭文件


 打开文件

文件句柄 = open('文件路径', '模式')
Copy after login

指定文件编码

文件句柄= open('文件路径','模式',encoding='utf-8')
Copy after login

 为了防止忘记关闭文件,可以使用上下文管理器来打开文件

with open('文件路径','模式') as 文件句柄:
Copy after login

Copy after login

打开文件的模式有:

  • r,只读模式(默认)。

  • w,只写模式。【不可读;不存在则创建;存在则删除内容;】

  • a,追加模式。【可读;   不存在则创建;存在则只追加内容;】

  • r+,可读写文件。【可读;可写;可追加】

  • w+,写读

"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)

  • rU

  • r+U

"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)

  • rb

  • wb

  • ab


 关闭文件

文件句柄.close()
Copy after login

操作文件:

detach

#占位
Copy after login

fileno(返回文件描述符,用于底层操作系统的 I/O 操作)

fid = 文件句柄.fileno()print(fid)
Copy after login

flush(刷新缓冲区,将缓冲区中的数据立刻写入文件)

文件句柄.flush()
Copy after login

isatty(判断文件是否连接到一个终端设备,返回布尔值)

文件句柄.isatty()
Copy after login

read(从文件中读取指定的字符数,默认读取全部)

str = 文件句柄.read()      #读取整个文件str1 = 文件句柄.read(10)   #读取文件前10个字符
Copy after login

readable(判断文件是否可读,返回布尔值)

文件句柄.readable()
Copy after login

readline(每次最多读取一行数据,每行的最后包含换行符'\n')

print(文件句柄.readline())   #读取第一行数据print(文件句柄.readline(3))  #读取第二行前3个字符print(文件句柄.readline())   #读取第二行剩余字符print(文件句柄.readline())   #读取第三行
Copy after login

seek(移动文件读取的指针,如果文件中包含中文,移动指针必须是3的倍数,不然会报错,因为一个中文字符等于3个字节)

文件句柄.seek(6)
Copy after login

seekable(判断文件指针是否可用,返回布尔值)

文件句柄.seekable()
Copy after login

tell(获取指针位置)

文件句柄.tell()
Copy after login

truncate(截断,把指针后面的内容删除,并写入文件,要在可写模式下操作)

f = open('text.txt','r+',encoding='utf-8')
f.seek(9)   #把指针移动到第9个字节后面(即第3个中文后面)f.truncate()  #把第3个中文后面的字符删除,并写入文件f.close()
Copy after login

writable(判断文件是否可写,返回布尔值)

文件句柄.writable()
Copy after login

write(把字符串写入文件,并返回字符数)

文件句柄.write('字符串')
Copy after login

The above is the detailed content of 详解python3文件操作步骤. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!