Python file processing

Source: Internet
Author: User

First, the way the file is opened

  File Open method: Open (Name[,mode][,buf][,encoding])

Parameter explanation: Name file path

Mode open mode

BUF: Buffer buffering size

Encoding: encoding format for files

How to open the file:

  

 

Second, the file read

Read (): Read the entire file

Read (size): reads a size byte

ReadLine ([size]): reads a row

ReadLines ([size]): Reads buffering bytes, returns a list of each row

ITER (): Using iterators to read files

Give a text file: E://me.txt, which reads as follows:

                                say to yourself listen                                 to--- sanmao if there is an afterlife, to do a tree, stand for eternity, no joys and sorrows posture, half in the Earth serene, half in the wind, half-shaded, half bathed in the sun, very quiet very proud, never rely on, never look for. 
#使用read () method
F=open ("E://me.txt","R", encoding="Utf-8");d ATA=F.read ();Print(data);

The results of the implementation are as follows:
say it to yourself.
---sanmao
If there is an afterlife,
to make a tree,
stand in eternity,
without a joys and sorrows posture,
half Serene in the Earth,
half in the wind to publicize,
half a shade,
half bathed in sunshine,
very silent and very proud,
never rely on, never look for.

#使用read (size) method
F=open ("e://me.txt","R", encoding="  Utf-8");d ata=f.read (in); Print (data);

The results of the implementation are as follows:

Say it to yourself.
---Sanmao
Such as

#使用readline () method

F=open ("e://me.txt","R", encoding="utf-8  ");d ata=f.readline (); Print (data);

The results of the implementation are as follows:

Say it to yourself.

#使用readline (30) Method:

f=Open ("E://me.txt","R",encoding="Utf-8");
Data=f.readline (10);
Data1=f.readline (10);
print (data);
Print (DATA1);

The results of the implementation are as follows:

Said
Listen to yourself.

#使用readlines () method

F=open ("e://me.txt","R", encoding="utf-8  ");d ata=f.readlines (); Print (data);

The results of the implementation are as follows:

[' \ufeff\t\t\t\t\t\t\t\t said to himself, ' \t\t\t\t\t\t\t\t---sanmao ', ' if there is an afterlife, \ n ', ' To do a tree, \ n ', ' stand for eternity, \ n ', ' No joys and sorrows posture, \ n ', ' Half in the Earth serene, \ n ', ' Half in the wind, \ n ', ' Half in the shade, \ n ', ' Half bathed in sunshine, \ n ', ' very silent very proud, \ n ', ' never relied on, never looked for. ‘]

#使用readlines (size) method

F=open ("e://me.txt","R", encoding="utf-8  ");d ata=f.readlines (1);d ata1=f.readline (2);d ata2=f.readlines (3 ); Print (data); Print (data1); Print (DATA2);

The results of the implementation are as follows:

[' \ufeff\t\t\t\t\t\t\t\t said to himself ']

[' \t\t\t\t\t\t---sanmao \ n ']

Found ReadLines (size) The result of this method is not the same as our expectation.

This is due to the presence of an IO buffer with a buffer size of: 8192.

#使用迭代器读取文件

F=open ("e://me.txt","R", encoding="utf-8  "); Iter_f=iter (f); # Convert a file object to an iterator object  for inch iter_f:     Print (i,end="");

The result of the execution is:

Say it to yourself.
---Sanmao
If there is an afterlife,
To make a tree,
Stand in eternity,
Without a joys and sorrows posture,
Half serene in the Earth,
Half in the wind to publicize,
Half a shade,
Half bathed in sunshine,
Very silent and very proud,
Never rely on, never look for.

Using Read ()/readline ()/readlines () will load the entire file into memory, greatly wasting memory, and we can use iterators to save memory.

Third, file write

Write (str): Writes a string to a file

Writelines (strings): Write multiple lines to a file

#使用write () method
F=open ("e://me.txt","a+", encoding="utf-8 ";d ata="\ n \ nthe dream, can be hype "; f.write (data);

At this point, only the data in memory is modified, and the data on the disk has not been modified. Only the Flush ()/close () method is transferred, and the modified data is written to disk.

Use the Writelines () method;
F=open ("E://me.txt","A +", encoding="Utf-8");d ata1=[    "Heart, if there is no place to live, where are the wandering",    "When you moths, you must be very happy and happy.",    "today's things, with all your heart, try to do, regardless of the results, should be happy to sleep in bed. "]f.writelines (DATA1);
F.close ()

at this point, only the data in memory is modified, and the data on the disk has not been modified. Only the Flush ()/close () method is transferred, and the modified data is written to disk.

Python Write Disk Time
1. Actively call the Close ()/flush () method, write cache synchronization to disk
2. Write data volume is greater than or equal to write cache, write cache is synchronized to disk

Iv. File Pointers

File pointer operation:

Seek (Offset,[whence])

Offset: Offsets, can be a negative number

Whence: Offset equivalent position, the value of the following three:

1, OS. Seek_set: Relative file start location

2, OS. Seek_cur: Relative file Current Location

3, OS. Seek_end: Relative file End Location

Tell (): The function of the tell function is to display the current pointer position

      

Import os;f=open ("e://me.txt","r+", encoding=" Utf-8 " ); F.read (3); Print (F.tell ()); F.seek (0,os. Seek_set)print(F.tell ());

The result of the execution is:
5
3

Using the Seek () function, we can define any location to the file.

V. Closing of documents

Why would you like to close the file?

1. Synchronizing write cache to disk

2, Linux system, the number of open files per process is limited, if more than the system limits, and then open the file will fail.

Closing the file is actually called the close () function.

Python file processing

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.