Python open()文件处理使用介绍
1. open()语法
open(file[, mode[, buffering[, encoding[, errors[, newline[, closefd=True]]]]]])
open函数有很多的参数,常用的是file,mode和encoding
file文件位置,需要加引号
mode文件打开模式,见下面3
buffering的可取值有0,1,>1三个,0代表buffer关闭(只适用于二进制模式),1代表line buffer(只适用于文本模式),>1表示初始化的buffer大小;
encoding表示的是返回的数据采用何种编码,一般采用utf8或者gbk;
errors的取值一般有strict,ignore,当取strict的时候,字符编码出现问题的时候,会报错,当取ignore的时候,编码出现问题,程序会忽略而过,继续执行下面的程序。
newline可以取的值有None, \n, \r, ”, ‘\r\n',用于区分换行符,但是这个参数只对文本模式有效;
closefd的取值,是与传入的文件参数有关,默认情况下为True,传入的file参数为文件的文件名,取值为False的时候,file只能是文件描述符,什么是文件描述符,就是一个非负整数,在Unix内核的系统中,打开一个文件,便会返回一个文件描述符。
2. Python中file()与open()区别
两者都能够打开文件,对文件进行操作,也具有相似的用法和参数,但是,这两种文件打开方式有本质的区别,file为文件类,用file()来打开文件,相当于这是在构造文件类,而用open()打开文件,是用python的内建函数来操作,建议使用open
3. 参数mode的基本取值
Character | Meaning |
‘r' | open for reading (default) |
‘w' | open for writing, truncating the file first |
‘a' | open for writing, appending to the end of the file if it exists |
‘b' | binary mode |
‘t' | text mode (default) |
‘+' | open a disk file for updating (reading and writing) |
‘U' | universal newline mode (for backwards compatibility; should not be used in new code) |
r、w、a为打开文件的基本模式,对应着只读、只写、追加模式;
b、t、+、U这四个字符,与以上的文件打开模式组合使用,二进制模式,文本模式,读写模式、通用换行符,根据实际情况组合使用、
常见的mode取值组合
r或rt 默认模式,文本模式读 rb 二进制文件 w或wt 文本模式写,打开前文件存储被清空 wb 二进制写,文件存储同样被清空 a 追加模式,只能写在文件末尾 a+ 可读写模式,写只能写在文件末尾 w+ 可读写,与a+的区别是要清空文件内容 r+ 可读写,与a+的区别是可以写到文件任何位置
4. 测试
测试文件test.txt,内容如下:
Hello,Python www.jb51.net This is a test file
用一小段代码来测试写入文件直观的显示它们的不同
test = [ "test1\n", "test2\n", "test3\n" ] f = open("test.txt", "a+") try: #f.seek(0) for l in test: f.write(l) finally: f.close()
a+、w+和r+模式的区别(测试后还原test.txt)
a+模式
# cat test.txt Hello, Python www.jb51.net This is a test file test1 test2 test3
w+模式
# cat test.txt test1 test2 test3
r+模式
在写入文件前,我们在上面那段代码中加上一句f.seek(0),用来定位写入文件写入位置(文件开头),直接覆盖字符数(注意\n也是一个字符)
# cat test.txt test1 test2 test3 inuxeye.com This is a test file
注意:r+模式打开文件时,此文件必须存在,否则就会报错,‘r'模式也如此
其他测试
>>> f = open('test.txt') >>> f.read() #读取整个文件,字符串显示 'Hello,Python\nwww.jb51.net\nThis is a test file\n' >>> f.read() #指针在文件末尾,不能再读取内容 ''
>>> f = open('test.txt') >>> f.readline() #一次读一行,指针在该行末尾 'Hello,Python\n' >>> f.tell() #改行的字符长度 13 >>> f.readline() 'www.jb51.net\n' >>> f.tell() 30 >>> f.readline() 'This is a test file\n' >>> f.tell() 50 >>> f.readline() '' >>> f.tell() #指针停在最后一行 50
>>> f = open('test.txt') >>> f.readlines() #读取整个文件,以列表显示 ['Hello,Python\n', 'www.jb51.net\n', 'This is a test file\n'] >>> f.tell() #指针在最后一行 50
>>> f = open('test.txt','w') #覆盖创建新文件 >>> f.write('Hello,Python!') #如果写入内容小于1024,会存在内存,否则需要刷新 >>> f.flush() #写入到硬盘 >>> f.close() #关闭文件会自动刷新 >>> f.write('Hello,Linuxeye') #关闭后,写失败,提示文件已经关闭 Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: I/O operation on closed file

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".
