Python Learning file operations

Source: Internet
Author: User

One, Python open file
#=====================python file opening mode open () =====================#Open (Filename,type) type= "R" opens the file as read-only, the file must existFile_r=open ("E:\\python\\hello.txt","R");#Open (Filename,type) type= "W"#1. Open the file as write-only, and the file will be created if it does not exist.#2. If the file exists and has content, the content will be emptiedFile_w=open ("E:\\python\\hello_w.txt","W");#Open (Filename,type) type= "A" opens the file in Append modeFile_a=open ("E:\\python\\hello_w.txt","a");#Open (Filename,type) type= "r+" or type= "w+" opens the file in a read-write mannerFile_rr=open ("E:\\python\\hello_w.txt","r+");#Open (Filename,type) type= "A +" opens the file in append and read-write modeFile_aa=open ("E:\\python\\hello_w.txt","A +");

Second, Python read the file

 

#=====================python file read by Read () =====================#Read () reads all read (size) reads the specified number of charactersdefreadtest (): File_r=open ("E:\\python\\hello.txt","R"); STR=File_r.read (); Print(str); File_r.close ();#ReadLine () reads a row of ReadLine (size) reads the size characters in a row (regardless of whether the size is greater than the number of characters in a row, the number of characters in a row is always returned)defreadlinetest (): File_r=open ("E:\\python\\hello.txt","R"); STR=file_r.readline (2); Print(str); File_r.close ();#readlines () reads all files (IO. Default_buffer_size), returns a list of each row (if the file is very memory-intensive)defreadlinestest (): File_r=open ("E:\\python\\hello.txt","R"); STR=file_r.readlines (18); Print(str); File_r.close ();#iter: Using iterators to read filesdefitertest (): File_r=open ("E:\\python\\hello.txt","R"); Iter_f=iter (File_r);#Convert the file to an iterator,lines=0;  forLineinchIter_f:Print(line); Lines+=1; Print(lines); File_r.close ();

Third, Python writes the file

  The concept of a file buffer is first understood when introducing file writes.

CPU in the operation of physical memory data (read and write) speed is very time-consuming, our computer in order to improve operational efficiency, our computer cup core to the data parameters of a cache area, Cup will first operate the cache area of data, will be at some point in the cache area of data written to physical memory.

So we have to mention two methods of close () and flush () when the file is written;

#===================== file closes close () ====================
# Write cached data to disk
# The number of open files per process in a Linux system is limited (if the limit is exceeded, the file will fail to open) so be sure to close the file after each use of the file
#===================== Flush () ====================
# Write cached data to disk

About the CPU cache code Demo:
Create an empty file Hello.txt
def writertest ():    file=open ("e:\\python\\hello.txt","w " );    File.write ("hello Word");

Result: The hello.txt is still empty

use: Close () will flush () method
defwritertest (): File=open ("E:\\python\\hello.txt","W"); #writes data to a disk file, but generally our cup has a file buffer, and the data is generally written to the CPU's file buffer.     #if the amount of data written to a character is greater than or equal to the size of the CPU's file buffer, the CPU will automatically write that data to the secondary disk file, the remaining characters we still need    #The flush () or close () method is called to write all data to the disk file. File.write ("Hello Word"); #call Flush () tells the CPU to write the data in the file cache to the disk file, or call the Close () F method directlyFile.flush (); File.close ();

Result: Open hello.txt content as Hello Word

writerlines (str): Write multiple lines to a file
defwriterlinestest (): 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 Pointers

#=================== file Pointer ===================
#文件读写的问题
#写入文件后, you must open to read the content that was written, and after you read the file, you cannot reread the read content again

#文件读取原理
#python在进行文件读取过程中, a pointer to the file is generated that records where the current file is being read.

#如何操作文件指针
#seek (offert,whence): Move the file pointer offset: The offset can be a negative number. Whence: Offset relative position
#os. Seek_set: Relative file start location
#os. Seek_cur: Relative file Current Location
#os. Seek_end: Relative file End Position
#如果文件指针的偏移量大于文件字符个数程序将报错

Importos;defseektest (): File=open ("E:\\python\\hello.txt","r+"); STR=file.read (3);#read three characters     Print(str); Index=file.tell ();#gets the position of the current file pointer     Print(index);#3     #Requirements: Move the file pointer to the start positionFile.seek (0,os.     Seek_set); Index=File.tell (); Print(index);#0     #Requirements: Move the file pointer to the end positionFile.seek (0,os.     Seek_end); Index=File.tell (); Print(index);#9File.close ();

Attention:

Python3 does not allow non-binary open files, relative to the end of the file location, which is the original text of the document:


(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)

Python Learning file operations

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.