Explanation of file read/write and Related File object methods in Python Programming,

Source: Internet
Author: User

Explanation of file read/write and Related File object methods in Python Programming,

Python file read/write

The built-in functions for reading and writing files in python are open or file.

File_hander (file handle or object) = open (filename, mode)

Mode:

Description

R read-only

R + read/write

W write, delete the source file first, and re-write. If the file does not exist, create

W + read/write: First Delete the source file and re-write it. If the file does not exist, create it (you can write it out)

Read files:

>>> fo = open("/root/a.txt")>>> fo
<open file '/root/a.txt', mode 'r' at 0x7f5095dec4e0>
>>> fo.read()
'hello davehe\ni am emily\nemily emily\n'
>>> Fo. close () >>> fo. read () # The object is closed and cannot be read.
Traceback (most recent call last): File "<stdin>", line 1, in <module>ValueError: I/O operation on closed file


>>> f1 = file("/root/a.txt")         >>> f1.read()
'hello davehe\ni am emily\nemily emily\n'
>>> f1.close()

Write File:

root@10.1.6.200:~# ls -l new.txt
ls: cannot access new.txt: No such file or directory
>>> Fnew = open ("/root/new.txt", 'w') w parameter file is not created> fnew. write ('Hello \ n I am dave ')

In this case, viewing the file data is still in the cache and does not actually fall into the file.

root@10.1.6.200:~# cat new.txt root@10.1.6.200:~#

As long as I close the file, the data will be written from the cache area to the file.

>>> fnew.close()root@10.1.6.200:~# cat new.txt 
hello i am dave

If you use the w parameter again, the file will be cleared. Therefore, use this parameter with caution.

>>> fnew = open("/root/new.txt","w")
root@10.1.6.200:~# cat new.txt root@10.1.6.200:~#

The mode uses the r + parameter:

>>> fnew = open("/root/new.txt",'r+')>>> fnew.read()
'hello dave'
>>> fnew.write('i am dave')>>> fnew.close()
root@10.1.6.200:~# cat new.txt 
hello davei am dave

When you open the file and write it directly, you will find that ooo replaces the starting letter, because the above reading operation uses a pointer to write it after writing. This time, it is written directly from the beginning.

>>> fnew = open("/root/new.txt",'r+')>>> fnew.write('ooo')>>> fnew.close()
root@10.1.6.200:~# cat new.txt 
ooolo davei am dave

File object Method
The following file object Method

  • FileObject. close ()
  • String = FileObject. readline ([size])
  • List = FileObject. readlines ([size])
  • String = FileObject. read ([size]) read: read all data
  • FileObject. next ()
  • FileObject. write (string)
  • FileObject. writelines (List)
  • FlieObject. seek (offset, option)
  • FlieObject. flush () Submit for update
>>> For I in open ("/root/a.txt"): You can use open to return variable of the iteration type and read data row by row... print I...
hello davehei am emilyemily emily

FileObject. readline: a row that reads files each time. size indicates that each row reads size bytes until the end of the row. An empty string is read when the range is exceeded.

>>> f1 = open("/root/a.txt")>>> f1.readline()
'hello davehe\n'
>>> f1.readline()
'i am emily\n'
>>> f1.readline()
'emily emily\n'
>>> f1.readline()''>>> f1.readline()''>>>f1.close()

FileObject. readlines: returns a list.

>>> f1 = open("/root/a.txt")>>> f1.readlines()
['hello davehe\n', 'i am emily\n', 'emily emily\n']''

FileObject. next: returns the current row and pointer the file to the next row. If the row is out of range, an alarm is triggered to stop iteration.

>>> f1 = open("/root/a.txt")>>> f1.next()
'hello davehe\n'
>>> f1.next()
'i am emily\n'
>>> f1.next()
'emily emily\n'
>>> f1.next()
Traceback (most recent call last): File "<stdin>", line 1, in <module>StopIteration

FileObject. write: write and the following writelines determine whether to clear all original data in the file before writing. Re-writing new content depends on the file opening mode.

FileObject. writelines (List): multi-row write, which is more efficient and faster than write. You can use write to write a small amount of data.

>>> l = ["python\n","python\n","python\n"]>>> f1 = open('/root/a.txt','a')>>> f1.writelines(l)>>> f1.close()
root@10.1.6.200:~# cat a.txt 
hello davehei am emilyemily emilypythonpythonpython

FlieObject. seek (offset, option): You can move the file pointer to different positions in the file.

The default position is 0, which indicates that the value starts from the beginning of the file (that is, the absolute offset), 1 indicates that the value starts from the current position, and 2 indicates that the value starts from the end of the file.

>>> f1 = open('/root/a.txt','r+')>>> f1.read()
'hello davehe\ni am emily\nemily emily\npython\npython\npython\n'
>>> F1.seek (0, 0) pointer refers to the beginning, reading >>> f1.read ()
'hello davehe\ni am emily\nemily emily\npython\npython\npython\n'
>>> F1.read () ''>>> f1.seek () >>> f1.seek () pointer to the end, reading >>> f1.read ()''

Next, look at a small hacker and check whether emily appears several times in a.txt.

root@10.1.6.200:~# vim file.py 
#!/usr/bin/env pythonimport ref1 = open('/root/a.txt')count = 0for 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()
root@10.1.6.200:~# cat a.txt 
hello davehei am emilyemily emily
root@10.1.6.200:~# python file.py 
this is have 3 emily

Articles you may be interested in:
  • Python read/write ini configuration file Method Instance Analysis
  • Python file read/write method summary
  • How to read and write configuration files in Python
  • How to read and write INI files using Python
  • How to read and write binary files using python
  • Introduction to reading and writing Excel files using Python
  • Example of reading and writing an INI file from python (reading and writing a file from python)
  • Python file read/write operations
  • Python read/Write File Operation example Program
  • Python read/write Excel files

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.