Home Backend Development Python Tutorial Python编程中的文件读写及相关的文件对象方法讲解

Python编程中的文件读写及相关的文件对象方法讲解

Jun 10, 2016 pm 03:06 PM
python document Read and write

python文件读写

python 进行文件读写的内建函数是open或file

file_hander(文件句柄或者叫做对象)= open(filename,mode)

mode:

模式    说明

r        只读

r+      读写

w       写入,先删除源文件,在重新写入,如果文件没有则创建

w+     读写,先删除源文件,在重新写入,如果文件没有则创建(可以写入写出)

读文件:

>>> fo = open("/root/a.txt")
>>> fo
Copy after login

<open file '/root/a.txt', mode 'r' at 0x7f5095dec4e0>
Copy after login

>>> fo.read()
Copy after login

'hello davehe\ni am emily\nemily emily\n'
Copy after login
Copy after login

>>> fo.close()
>>> fo.read()                     #对象已关闭,在读取就读不到
Copy after login

Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file
Copy after login


>>> f1 = file("/root/a.txt")         
>>> f1.read()
Copy after login

'hello davehe\ni am emily\nemily emily\n'
Copy after login
Copy after login

>>> f1.close()
Copy after login

写文件:

root@10.1.6.200:~# ls -l new.txt
Copy after login

ls: cannot access new.txt: No such file or directory
Copy after login

>>> fnew = open("/root/new.txt",'w')  w参数文件没有则创建
>>> fnew.write('hello \n i am dave')
Copy after login

这时查看文件数据其实还只是在缓存区中,没有真正落到文件上.

root@10.1.6.200:~# cat new.txt 
root@10.1.6.200:~#
Copy after login
Copy after login

只要我把文件关闭,数据会从缓存区写到文件里

>>> fnew.close()
root@10.1.6.200:~# cat new.txt 
Copy after login

hello 
i am dave
Copy after login

再次使用w参数,文件会被清空,所以用该参数需要谨慎.

>>> fnew = open("/root/new.txt","w")
Copy after login

root@10.1.6.200:~# cat new.txt 
root@10.1.6.200:~#
Copy after login
Copy after login

mode使用r+参数:

>>> fnew = open("/root/new.txt",'r+')
>>> fnew.read()
Copy after login

'hello dave'
Copy after login

>>> fnew.write('i am dave')
>>> fnew.close()
Copy after login

root@10.1.6.200:~# cat new.txt 
Copy after login
Copy after login

hello davei am dave
Copy after login

这次打开文件,直接写入,会发现ooo替换开头字母,因为上面读取操作使用了指针在写就写在后面.而这次是直接从头写入.

>>> fnew = open("/root/new.txt",'r+')
>>> fnew.write('ooo')
>>> fnew.close()
Copy after login

root@10.1.6.200:~# cat new.txt 
Copy after login
Copy after login

ooolo davei am dave

Copy after login

文件对象方法
下面文件对象方法

  • FileObject.close()
  • String=FileObject.readline([size])
  • List = FileObject.readlines([size])
  • String = FileObject.read([size]) read:读取所有数据
  • FileObject.next()
  • FileObject.write(string)
  • FileObject.writelines(List)
  • FlieObject.seek(偏移量,选项)
  • FlieObject.flush() 提交更新
>>> for i in open("/root/a.txt"):  用open可以返回迭代类型的变量,可以逐行读取数据
...   print i
... 
Copy after login

hello davehe
i am emily
emily emily

Copy after login

FileObject.readline: 每次读取文件的一行,size是指每行每次读取size个字节,直到行的末尾,超出范围会读取空字符串

>>> f1 = open("/root/a.txt")
>>> f1.readline()
Copy after login

'hello davehe\n'
Copy after login
Copy after login

>>> f1.readline()
Copy after login
Copy after login

'i am emily\n'
Copy after login
Copy after login

>>> f1.readline()
Copy after login
Copy after login

'emily emily\n'
Copy after login
Copy after login

>>> f1.readline()
''
>>> f1.readline()
''
>>>f1.close()
Copy after login

FileObject.readlines:返回一个列表

>>> f1 = open("/root/a.txt")
>>> f1.readlines()
Copy after login

['hello davehe\n', 'i am emily\n', 'emily emily\n']''
Copy after login

FileObject.next:返回当前行,并将文件指针到下一行,超出范围会给予警示,停止迭代.

>>> f1 = open("/root/a.txt")
>>> f1.next()
Copy after login

'hello davehe\n'
Copy after login
Copy after login

>>> f1.next()
Copy after login
Copy after login
Copy after login

'i am emily\n'
Copy after login
Copy after login

>>> f1.next()
Copy after login
Copy after login
Copy after login

'emily emily\n'
Copy after login
Copy after login

>>> f1.next()
Copy after login
Copy after login
Copy after login

Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
StopIteration
Copy after login

FileObject.write:write和后面writelines在写入前会是否清除文件中原来所有的数据,在重新写入新的内容,取决于打开文件的模式.

FileObject.writelines(List):多行写,效率比write高,速度更快,少量写入可以使用write

>>> l = ["python\n","python\n","python\n"]
>>> f1 = open('/root/a.txt','a')
>>> f1.writelines(l)
>>> f1.close()
Copy after login

root@10.1.6.200:~# cat a.txt 
Copy after login
Copy after login

hello davehe
i am emily
emily emily
python
python
python
Copy after login

FlieObject.seek(偏移量,选项):可以在文件中移动文件指针到不同的位置.

位置的默认值为0,代表从文件开头算起(即绝对偏移量),1代表从当前位置算起,2代表从文件末尾算起.

>>> f1 = open('/root/a.txt','r+')
>>> f1.read()
Copy after login

'hello davehe\ni am emily\nemily emily\npython\npython\npython\n'
Copy after login
Copy after login

>>> f1.seek(0,0)   指针指到开头,在读
>>> f1.read()
Copy after login

'hello davehe\ni am emily\nemily emily\npython\npython\npython\n'
Copy after login
Copy after login

>>> f1.read()
''
>>> f1.seek(0,0)
>>> f1.seek(0,2)   指针指到末尾,在读
>>> f1.read()
''
Copy after login

下面看个小实例,查找a.txt中emily出现几次

root@10.1.6.200:~# vim file.py 
Copy after login

#!/usr/bin/env python
import re
f1 = open('/root/a.txt')
count = 0
for s in f1.readlines():
  li = re.findall("emily",s)
  if len(li) > 0:
    count = count + len(li)
print "this is have %d emily" % count 
f1.close()
Copy after login

root@10.1.6.200:~# cat a.txt 
Copy after login
Copy after login

hello davehe
i am emily
emily emily
Copy after login

root@10.1.6.200:~# python file.py 
Copy after login

this is have 3 emily

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
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)

Google AI announces Gemini 1.5 Pro and Gemma 2 for developers Google AI announces Gemini 1.5 Pro and Gemma 2 for developers Jul 01, 2024 am 07:22 AM

Google AI has started to provide developers with access to extended context windows and cost-saving features, starting with the Gemini 1.5 Pro large language model (LLM). Previously available through a waitlist, the full 2 million token context windo

How to download deepseek Xiaomi How to download deepseek Xiaomi Feb 19, 2025 pm 05:27 PM

How to download DeepSeek Xiaomi? Search for "DeepSeek" in the Xiaomi App Store. If it is not found, continue to step 2. Identify your needs (search files, data analysis), and find the corresponding tools (such as file managers, data analysis software) that include DeepSeek functions.

How do you ask him deepseek How do you ask him deepseek Feb 19, 2025 pm 04:42 PM

The key to using DeepSeek effectively is to ask questions clearly: express the questions directly and specifically. Provide specific details and background information. For complex inquiries, multiple angles and refute opinions are included. Focus on specific aspects, such as performance bottlenecks in code. Keep a critical thinking about the answers you get and make judgments based on your expertise.

How to search deepseek How to search deepseek Feb 19, 2025 pm 05:18 PM

Just use the search function that comes with DeepSeek. Its powerful semantic analysis algorithm can accurately understand the search intention and provide relevant information. However, for searches that are unpopular, latest information or problems that need to be considered, it is necessary to adjust keywords or use more specific descriptions, combine them with other real-time information sources, and understand that DeepSeek is just a tool that requires active, clear and refined search strategies.

How to program deepseek How to program deepseek Feb 19, 2025 pm 05:36 PM

DeepSeek is not a programming language, but a deep search concept. Implementing DeepSeek requires selection based on existing languages. For different application scenarios, it is necessary to choose the appropriate language and algorithms, and combine machine learning technology. Code quality, maintainability, and testing are crucial. Only by choosing the right programming language, algorithms and tools according to your needs and writing high-quality code can DeepSeek be successfully implemented.

How to use deepseek to settle accounts How to use deepseek to settle accounts Feb 19, 2025 pm 04:36 PM

Question: Is DeepSeek available for accounting? Answer: No, it is a data mining and analysis tool that can be used to analyze financial data, but it does not have the accounting record and report generation functions of accounting software. Using DeepSeek to analyze financial data requires writing code to process data with knowledge of data structures, algorithms, and DeepSeek APIs to consider potential problems (e.g. programming knowledge, learning curves, data quality)

The Key to Coding: Unlocking the Power of Python for Beginners The Key to Coding: Unlocking the Power of Python for Beginners Oct 11, 2024 pm 12:17 PM

Python is an ideal programming introduction language for beginners through its ease of learning and powerful features. Its basics include: Variables: used to store data (numbers, strings, lists, etc.). Data type: Defines the type of data in the variable (integer, floating point, etc.). Operators: used for mathematical operations and comparisons. Control flow: Control the flow of code execution (conditional statements, loops).

Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Oct 11, 2024 pm 08:58 PM

Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid

See all articles