python-file Operations

Source: Internet
Author: User
Tags readline

1, file common operation 1.1, read mode
With open (' Myx.txt ', ' R ', encoding= ' utf-8 ') as F:  #open函数默认是读默认, so R can be omitted, but for specification it is best to write clearly which way to open    print (F.read ())
1.2. Write mode
With open (' Xie.txt ', ' W ', encoding= ' utf-8 ') as F:  #文件已写模式打开    f.write (' 123\n ')    f.write (' 456\n ')    print (F.read ()) #由于模式之间不兼容, if the file is only opened in write mode, the read operation will error    #io. Unsupportedoperation:not readable
1.3. Append mode
With open (' Xie.txt ', ' a ', encoding= ' utf-8 ') as F:  #和写模式不同, append mode open file, will not overwrite the original file content, will only be added after the file, if opened in W mode, will empty the original contents of the file , rewrite the    f.write (' 789\n ') #对于写与追加模式, you can write    f.write (' aaa\n ')    print (F.read ()) #追加模式也同样不能进行读操作    #io. Unsupportedoperation:not readable

  Summarize:

File open most commonly used three modes for read, write, append. The default is the open function in read mode to work, in read mode can read the contents of the file, write and append mode can modify the file, the difference is that the read mode after opening the file, the original file content is emptied, add new content, and the Append mode will not empty the original content, New additions are added at the end of the file, as well as how to combine the R, W, and a modes, as described in modifying the file.

2, read the relevant operation of the mode 2.1, read operation
With open (' Myx.txt ', ' R ', encoding= ' utf-8 ') as F:    print (F.read ()) #read操作会一次性将文件全部内容读取到内存中    print ('-------- I am the delimiter----------')    print (F.read ()) # Because of the presence of a file pointer, when the file is read to memory once, if it is read again before the pointer fallback operation, it will return a null value, indicating that the content has been read for the last time, this read does not display the content
2.2. ReadLine operation
With open (' Myx.txt ', ' R ', encoding= ' utf-8 ') as F:    print (F.readline ()) #与read操作一次性读取不同, the ReadLine operation reads only one line of content into memory at a time , the ReadLine method can be manipulated for each line of content    print ('--------I am delimiter----------') # #输出: Lyrics: The masterpiece of Gan Shi: Blackstar
2.3. ReadLines operation
With open (' Myx.txt ', ' R ', encoding= ' utf-8 ') as F:    Data=f.readlines () #区别于read于readline操作, the readlines operation is also a one-time read, The difference is that it puts the contents of the read into a list so that subsequent actions can be performed on the contents of the file as required by the    print (data) #<class ' list ' >
2.4, the correct way to read the file
#方式一, the file once through the ReadLines method read into memory, and then manipulate it, the method is suitable for small files, if the large file will be too large, resulting in the opening of the file speed is too slow, it is not recommended the way with open (' Myx.txt ', ' R ', encoding= ' Utf-8 ') as F:for index,line in Enumerate (F.readlines ()): Print (index,line,end= ") #end = ' Remove blank line ' output: 0 Lyrics: The masterpiece of Gan Shi: Blackstar 1 singing: Joker Xue 2 If the world is dark, I'm beautiful. 3 in love and retreat up to be consumed 4 regardless of the same is 5 and how wrong no matter 6 if like you always have someone flattery 7 around my humble may be able to fade 8 I don't really care about a lot of chances 9 like a giant fearless 10 indulgence in my Heart The Ghost 11 but I don't deserve 12 ugly don't turn on the lights 13 I want the love haunt in the dark stage 14 ugly in this ambiguous era 15 my presence like an accident 16 someone with a drop of tears will beauty jailbait 17 someone lost the title what will not 18 only want you hypocrisy 19 is not afraid of the devil right 20 If the script is written, who is more noble than who? 21 I can only be silent with the innocence of the beautiful 22 when the desire to start offs have more opportunities 23 like the dust of the fearless 24 turn into Ash who knows who is not worthy of 25 ugly can not turn on the lights 26 I want to haunt in the dark stage 27 ugly in this ambiguous era 28 my deposit In no accident 29 ugly actually see more do not blame 30 unbridled go to high force 31 that vulnerable to the white 32 ugly This is our time 33 I do not exist unexpectedly "' #第二种方法, data has been stale iterator instead of the list there is no subscript operation, this time each line read to the memory after the operation, Then release the memory, the next line of operation, save memory, recommend the way to operate with open (' Myx.txt ', ' R ', encoding= ' Utf-8 ') as f:for lines in F:print (line,end= ") ' Output lyrics: Blackstar sang: Joker Xue If the world is black I'm beautiful in love in the most is spending regardless of the same right and wrong don't matter if there's always someone flattering around me like you might fade in fact I don't care There are many opportunities, like giants, to indulge my demons, but I don't deserve ugly. Do not turn on the lights I want to love haunt in the dark stage ugly in this ambiguous era of myThere are people like accidental someone with a drop of tears will be the confidante jailbait someone lost the title what will not be afraid of the devil as long as you are hypocritical enough if the script is written well who is more noble I can only be silent to the beauty of this innocence when the desire to start offs have more opportunities to be like the dust of the fearless into ash who know who tube he Can you not turn on the lights I want to haunt in the dark stage ugly in this ambiguous era of my existence is not accidental ugly actually see more don't blame unbridled to high force on the white ugly This is our time I do not exist just unexpectedly "
2.5. Content Replacement
# with open (' Myx.txt ', ' R ', encoding= ' Utf-8 ') as f:# for     index,line in Enumerate (F.readlines ()): #         If index = = 9: #< C2/>print ('--------------------') #         print (index,line,end= ") with open (' Myx.txt ', ' R ', encoding= ' utf-8 ') as F:    count = 0 for line in    F:        if Count = =:            print ('----------------------')            count+=1            continue< C10/>print (line,end= ")        count+=1" output: Lyrics: Gan masterpiece: Blackstar sing: Joker Xue If the world is black I am beautiful in love in the most in the back and forth to be consumed regardless of the same right and wrong, it doesn't matter if you like There's always someone who flatters my humble might fade I don't really care if there's a lot of opportunity to be fearless like a giant----------------------            tenth row was replaced but I don't deserve ugly don't turn on the lights I want to haunt the dark stage ugly In this ambiguous era of my existence like an accident someone with a drop of tears will confidante jailbait someone lost the title of what will not be afraid of the devil if you are false enough if the script written well who than who noble I can only be silent to the beauty of the innocence when the desire to start offs have more opportunities like the dust of the fearless into ash who know who tube he worthy Can you not turn on the lights I want to haunt in the dark stage ugly in this ambiguous era of my existence is not accidental ugly actually see more don't blame unbridled to high force on the white ugly This is our time I do not exist just unexpectedly "
2.6. tell method and Seek method
With open (' Myx.txt ', ' R ', encoding= ' utf-8 ') as F:    print (F.tell ()) #tell方法可以只是当前文件指针所在位置, initially 0    print (f.read (10 )) #按照索引读取内容 0 to    print (F.tell ()) #当读取完毕后再次查看文件指针位置    print (F.read ()) #读取剩余的全部文件    print (F.tell ()) # Read at this time the file pointer position    print (F.read ()) #由于文件全部读取完毕, read again can only return null value    print (F.seek (0)) #将文件指针置为初始位置    print (F.tell ()    ) Print (F.read)    print (F.tell ()) #当读取文件后再次通过tell方法获取文件指针所在位置 "' Output 0 Lyrics: Gan masterpiece: 28 Blackstar singing: Joker Xue If the world is black I'm Beautiful in love Up to be consumed regardless of the same right and wrong, it doesn't matter if someone like you is always flattering around my humble might fade away I don't care if there's a lot of opportunities like giants to indulge in my heart ghosts but I don't deserve ugly don't turn on the lights I want to love haunt in the dark stage ugly In this ambiguous era of my existence like an accident someone with a drop of tears will confidante jailbait someone lost the title of what will not be afraid of the devil if you are false enough if the script written well who than who noble I can only be silent to the beauty of the innocence when the desire to start offs have more opportunities like the dust of the fearless into ash who know who tube he worthy Can you not turn on the lights I want to haunt in the dark stage ugly in this ambiguous era of my existence is not accidental ugly actually see more don't blame unbridled go to high force on the white ugly This is our time I don't exist just accidentally 107300 lyrics: Gan Composer: Blackstar singing: Joker Xue If 65 "
3. Other operations of the file 3.1. Encoding: Print file Encoding
>>> data.encoding ' Utf-8 '
3.2. Fino () returns the encoding of the operating system where the file handle is located basically does not use the Operation 3.3, Isatty () whether the file is an end device, the Linux system can be used to determine whether it is a TTY file 3.4. Name print file names
>>> data.name ' Yesterday.txt '
3.5. seekable () whether the pointer can be moved
>>> data.seekable () True
3.6. Flush () flush operation:

If you open the file in write mode, you do not have to write to the disk immediately after writing, if suddenly the power outage may not be written into the file in time, so you can flush the way to the disk

Example: You can print a progress bar when you install a program

Import time,sysfor i in range:    sys.stdout.write (' # ')    Sys.stdout.flush ()  #将 # is flushed to the screen    in real time Time.sleep (0.1)
3.7. closed determine if the file is closed
>>> data.closedfalse>>> data.close () >>> data.closedtrue
3.8. truncate () If you don't write anything, you're emptying the file.

Data.truncate (10) will retain only 10 bytes, the remainder will be deleted, and the truncate comes with a file pointer, regardless of whether you move to any position through seek, truncate will be deleted and retained in the initial position.

4. Modify a file

The modified file is divided into two modes:

1, read all the files into memory, and then modify, the typical representative of this way is the VIM program

2, read the file in line mode, and then put the new file after each line operation, this way to save memory footprint, similar to sed and awk operation

For file operations, there are other operations in addition to the typical r/w/a approach, which provides a brief introduction to these more common operations:

4.1. r+Read and write operations

the expression can be read and can be written, this means to read and append mode, if written, will write the content into the last

>>> data = open (' Test1.txt ', ' r+ ', encoding= ' utf-8 ')  #以读写模式打开文件 >>> data.readline () #对文件进行读操作 ' Back in the day \ n ' >>> data.readline () ' When I was young ' >>> data.readline () ' Listen to the Radio \ ' >>> data.readline () ' Waiting for my favorite song \ \ >>> data.write ('-------aaaaaaaaaa---------') #对该文件进行写操作 >>> data.readline () ' When it plays I sing it by myself \ >>> data.readline () ">>> data.seek (0) >>> data.read ()  #在重新载入文件进行读写会发现, The appended content will be put in the last ' old days ' when I was young, listening to the radio waiting for my favorite song, and when it played I sang it alone-------aaaaaaaaaa---------'
4.2. w+Read-write mode

Create a new file, enter the content, and then read the location of the file pointer, in the fallback, and then input, will find the inserted content, still in the last instead of through seek to reverse

>>> data = open (' Test1.txt ', ' w+ ', encoding= ' utf-8 ') #以w + mode open >>> data.write (' a-------1\n ') >> > Data.write (' a-------2\n ') >>> data.write (' a-------3\n ') >>> data.write (' a-------4\n ') #输入内容 >>> Data.seek (Ten) #跳转到第一行 >>> data.readline ()  #读取第二行 ' a-------2\n ' >>> Data.tell () > >> data.write (' a-------5\n ')  #插入新语句, should theoretically be inserted into line three >>> Data.seek (0) >>> data.read () ' A-------1\na-------2\na-------3\na-------4\na-------5\n '  #通过读取发现仍然是插入到最后一行, proving that moving the file pointer through seek also cannot change the w+ file input order
4.3. A +Append read mode

can be read during the append process  

>>> data = open (' Test1.txt ', ' A + ', encoding= ' utf-8 ') >>> data.read () ' >>> Data.tell () > >> data.seek (0) >>> >>> >>> data.write (' A----------6\n ') #将指针挪到开头后进行追加写操作 >> > Data.seek (0) >>> data.read ()  #重新读取文件发现, Append writes are still added in the original order ' a-------1\na-------2\na-------3\ Na-------4\na-------5\na----------6\n '
5. Binary Files

There are two ways for binary files, RB and WB, two of which use RB:

1, network transmission, socket transmission can only be encoded using binary format

2. The video file is open and must be opened in binary format

6. With Statement

To avoid forgetting to close a file after opening it, you can manage the context by using with:

>>> with open (' Tes2.txt ', ' W ') as F:f.write (' nnnnn\n ') ... 6

This way, when the with code finishes, the internal memory is automatically closed and the file is released, and multiple files can be opened at the same time

With open (' Tes2.txt ', ' W ') as F, open (' Test3.txt ', ' W ') as F2: #两个文件之间用 ', ' to split    f.write (' nnn\n ')    f2.write (' mmmm\n ‘)

  

  

  

  

  

  

  

python-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.