Python learning file operations,

Source: Internet
Author: User

Python learning file operations,
1. Open a file in python

#================================== Open python file () ==============================## open (fileName, type) type = "r" open a file in read-only mode, this file must exist file_r = open ("E: \ python \ hello.txt", "r"); # open (fileName, type) type = "w" #1. open the file in write-only mode. If the file does not exist, create the file #2. If the file exists and has content, file_w = open ("E: \ python \ hello_cmdtxt", "w"); # open (fileName, type) type = "a" open the file file_a = open ("E: \ python \ hello_1_txt", "a"); # open (fileName, type) by append) type = "r +" or type = "w +" open the file file_rr = open in read/write mode ("E: \ python \ hello_1_txt", "r + "); # open (fileName, type) type = "a +" open the file file_aa = open ("E: \ python \ hello_1_txt ", "a + ");

 

Ii. Reading files using python

 

#================================== Read () ==============================## read () read all read (size) read the specified number of characters def readTest (): file_r = open ("E: \ python \ hello.txt", "r"); str = file_r.read (); print (str); file_r.close (); # readline () read a row of readline (size) read the size characters in a row (no matter whether the size is greater than the number of characters in a row, the total number of characters in a row is returned) def readLineTest (): file_r = open ("E: \ python \ hello.txt", "r"); str = file_r.readline (2); print (str); file_r.close (); # readLines () read all files (io. DEFAULT_BUFFER_SIZE), returns the list of each row (if the file is very common and occupies a lot of memory space) def readLinesTest (): file_r = open ("E: \ python \ hello.txt ", "r"); str = file_r.readlines (18); print (str); file_r.close (); # iter: Use the iterator to read the file def IterTest (): file_r = open ("E: \ python \ hello.txt", "r"); iter_f = iter (file_r); # convert the file into an iterator, lines = 0; for line in iter_f: print (line); lines + = 1; print (lines); file_r.close ();

 

Iii. Writing python files

When introducing file writing, first understand the concept of a file cache.

Cpu data (read/write) in the physical memory is very time-consuming. In order to improve the running efficiency of our computer, our computer cup kernel will provide a high-speed cache area for data parameters, the cup will first operate on the data in the cache area, and then write the data in the cache area to the physical memory at a certain time point.

Therefore, when writing a file, we have to provide two methods: close () and flush ();

#================================== Close () ================================
# Writing cached data to a disk
# In linux, the number of files opened by each process is limited (if this limit is exceeded, opening the file will fail). Therefore, you must close the file after each file is used.
#=================================== Flush () ================================
# Writing cached data to a disk

Demo of cpu cache code:
Create an empty file hello.txt
def writerTest():    file=open("E:\\python\\hello.txt","w");    file.write("hello Word");

Result: hello.txt is still empty.

Use: close () will flush () method
Def writerTest (): file = open ("E: \ python \ hello.txt", "w"); # write data to a disk file, however, our cup usually has a file cache area, and data is usually first written into the File Cache area of the cpu. # If the data size of the written characters is greater than or equal to the File Cache size of the cpu, the cpu will automatically write the data to the next disk file, for the remaining characters, we still need to call the flush () or close () method to write all the data into the disk file. File. write ("hello Word"); # Call flush () to tell the cpu to write data in the file cache to the disk file, or directly call the close () f method file. flush (); file. close ();

Result: The hello.txt content is hello Word.

WriterLines (str): write multiple rows to a file
def writerLinesTest():    file=open("E:\\python\\hello.txt","w");    file.writelines("hello Word");    file.writelines(("hello_1","hello_2","hello_3"));    file.writelines(["hello_4","hello_5","hello_6"]);    file.close();

 

Iv. File pointer

#============================ File pointer ============================ =
# File read/write Problems
# After a file is written, it must be opened before the written content can be read. After the file is read, it cannot be read again.

# File Read Principle
# Python generates a file pointer during file reading, which records the location where the current file is read.

# How to operate file pointers
# Seek (offert, whence): Move the file pointer offset: the offset can be a negative number. Whence: relative offset position
# OS. SEEK_SET: Start position of the relative file
# OS. SEEK_CUR: relative to the current file location
# OS. SEEK_END: relative file end position
# If the offset of the file pointer is greater than the number of characters in the file, the program reports an error.

Import OS; def seekTest (): file = open ("E: \ python \ hello.txt", "r +"); str = file. read (3); # read three characters print (str); index = file. tell (); # obtain the current file pointer position print (index); #3 # requirement: Move the file pointer to the starting position file. seek (0, OS. SEEK_SET); index = file. tell (); print (index); #0 # requirement: Move the file pointer to the end of the file. seek (0, OS. SEEK_END); index = file. tell (); print (index); #9 file. close ();

Note:

Python3 does not allow non-binary files to be opened. It is relative to the position at the end of the file. This is the original document:
In text files (those opened without a b in the mode 
string), only seeks relative to the beginning of the file are allowed
(the exception being seeking to the very file end with seek(0, 2)).(https://docs.python.org/3.2/tutorial/inputoutput.html#methods-of-file-objects)

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.