Home Backend Development Python Tutorial Python open()文件处理使用介绍

Python open()文件处理使用介绍

Jun 10, 2016 pm 03:18 PM
open python File processing

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+的区别是可以写到文件任何位置
Copy after login

4. 测试
测试文件test.txt,内容如下:

Hello,Python
www.jb51.net
This is a test file
Copy after login

用一小段代码来测试写入文件直观的显示它们的不同

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()
Copy after login

a+、w+和r+模式的区别(测试后还原test.txt)
a+模式

# cat test.txt
Hello, Python
www.jb51.net
This is a test file
test1
test2
test3
Copy after login

w+模式

# cat test.txt
test1
test2
test3
Copy after login

r+模式
在写入文件前,我们在上面那段代码中加上一句f.seek(0),用来定位写入文件写入位置(文件开头),直接覆盖字符数(注意\n也是一个字符)

# cat test.txt
test1
test2
test3
inuxeye.com
This is a test file
Copy after login

注意:r+模式打开文件时,此文件必须存在,否则就会报错,‘r'模式也如此
其他测试

>>> f = open('test.txt')
>>> f.read() #读取整个文件,字符串显示
'Hello,Python\nwww.jb51.net\nThis is a test file\n'
>>> f.read() #指针在文件末尾,不能再读取内容
''
Copy after login
>>> 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
Copy after login
>>> f = open('test.txt')
>>> f.readlines() #读取整个文件,以列表显示
['Hello,Python\n', 'www.jb51.net\n', 'This is a test file\n']
>>> f.tell() #指针在最后一行
50
Copy after login
>>> 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 
Copy after login
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 admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is distinctIdistinguish related? Is distinctIdistinguish related? Apr 03, 2025 pm 10:30 PM

Although distinct and distinct are related to distinction, they are used differently: distinct (adjective) describes the uniqueness of things themselves and is used to emphasize differences between things; distinct (verb) represents the distinction behavior or ability, and is used to describe the discrimination process. In programming, distinct is often used to represent the uniqueness of elements in a collection, such as deduplication operations; distinct is reflected in the design of algorithms or functions, such as distinguishing odd and even numbers. When optimizing, the distinct operation should select the appropriate algorithm and data structure, while the distinct operation should optimize the distinction between logical efficiency and pay attention to writing clear and readable code.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to understand !x in C? How to understand !x in C? Apr 03, 2025 pm 02:33 PM

!x Understanding !x is a logical non-operator in C language. It booleans the value of x, that is, true changes to false, false changes to true. But be aware that truth and falsehood in C are represented by numerical values ​​rather than boolean types, non-zero is regarded as true, and only 0 is regarded as false. Therefore, !x deals with negative numbers the same as positive numbers and is considered true.

Troubleshooting tips for processing files in C language Troubleshooting tips for processing files in C language Apr 04, 2025 am 11:15 AM

Troubleshooting Tips for C language processing files When processing files in C language, you may encounter various problems. The following are common problems and corresponding solutions: Problem 1: Cannot open the file code: FILE*fp=fopen("myfile.txt","r");if(fp==NULL){//File opening failed} Reason: File path error File does not exist without file read permission Solution: Check the file path to ensure that the file has check file permission problem 2: File reading failed code: charbuffer[100];size_tread_bytes=fread(buffer,1,siz

What does sum mean in C language? What does sum mean in C language? Apr 03, 2025 pm 02:36 PM

There is no built-in sum function in C for sum, but it can be implemented by: using a loop to accumulate elements one by one; using a pointer to access and accumulate elements one by one; for large data volumes, consider parallel calculations.

Does H5 page production require continuous maintenance? Does H5 page production require continuous maintenance? Apr 05, 2025 pm 11:27 PM

The H5 page needs to be maintained continuously, because of factors such as code vulnerabilities, browser compatibility, performance optimization, security updates and user experience improvements. Effective maintenance methods include establishing a complete testing system, using version control tools, regularly monitoring page performance, collecting user feedback and formulating maintenance plans.

Copy and paste Love code Copy and paste Love code for free Copy and paste Love code Copy and paste Love code for free Apr 04, 2025 am 06:48 AM

Copying and pasting the code is not impossible, but it should be treated with caution. Dependencies such as environment, libraries, versions, etc. in the code may not match the current project, resulting in errors or unpredictable results. Be sure to ensure the context is consistent, including file paths, dependent libraries, and Python versions. Additionally, when copying and pasting the code for a specific library, you may need to install the library and its dependencies. Common errors include path errors, version conflicts, and inconsistent code styles. Performance optimization needs to be redesigned or refactored according to the original purpose and constraints of the code. It is crucial to understand and debug copied code, and do not copy and paste blindly.

How to obtain real-time application and viewer data on the 58.com work page? How to obtain real-time application and viewer data on the 58.com work page? Apr 05, 2025 am 08:06 AM

How to obtain dynamic data of 58.com work page while crawling? When crawling a work page of 58.com using crawler tools, you may encounter this...

See all articles