Explain the file operations in Python _python

Source: Internet
Author: User
Tags flush readline sleep in python

1. The method can be called must be objects, such as numbers, strings, lists, tuples, dictionaries, and even files are objects, Python everything is object.

 str1 = ' Hello '
 str2 = ' world '
 str3 = '. Join ([STR1,STR2])
 print (STR3)

2. Three basic file operation modes: R (Only-read), W (Only-write), A (append)

The process of manipulating files:

First, create a file object.

Second, the file method is invoked to operate.

Third, don't forget to close the file. (If the file is not closed, the content will be cached, although Python will automatically read the content to disk in the end, but in case of the habit of closing the file)

File File1

A faded picture,
seems to bring me a little memory.
Alley tail Grandpa sell hot noodle soup,
taste diffuse past the old backyard,
stray cat asleep in the swing, the
setting sun shone over his eyes;
the postcard from the same table,
lying quietly in the desk.

(1) R mode

Writing to content in read-only mode will cause an error.

 f = open (' File1 ', ' R ')
 F_read = F.read ()   #read是逐字符地读取, read can specify parameters, set how many characters to read, whether an English letter or a Chinese character is a character.
 print (F_read)
 f.close ()
 f = open (' File1 ', ' R ')
 F_read = F.readline () #readline只能读取第一行代码 the principle is to stop reading to the first line break.
 print (F_read)
 f.close ()
 f = open (' File1 ', ' R ')
 F_read = F.readlines () #readlines会把内容以列表的形式输出.
 print (F_read)
 f.close ()
 f = open (' File1 ', ' r ') for line in
 F.readlines () #使用for循环可以把内容按字符串输出.
   print (line) #输出一行内容输出一个空行, one row of content, one line of space ... Because there is a newline character behind each line of content in the file, and the print () statement itself can wrap, and if you do not want to output blank lines, you need to use the following statement: Print (Line.strip ())
 F.close ()

(2) W mode

All content in the file is emptied before the action is taken. For example, to write ' Hello World ' in file1, after the execution of File1, there is only one word ' Hello World '.

 f = open (' File1 ', ' W ', encoding= ' UTF8 ')  #由于Python3的默认编码方式是Unicode, so you need to call UTF8 when you write the file, save it in UTF8 way, At this time pycharm (the default encoding is UTF8) to read correctly, when reading files, the file is UTF8 format, Pycharm is also UTF8, no need to call.
 f_w = f.write (' Hello World ')
 print (f_w)  #有意思的是, which does not print ' Hello World ', print only how many characters to write
 F.close ()

(3) A mode

Unlike W mode, a mode does not empty the original content, but instead moves the cursor to the last position of the content and continues to write the new content. For example, at the end of the ' Hello World '

 f = open (' File1 ', ' a ')
 f_a = f.write (' Hello World ')
 print (f_a) #还是会打印写入的字符数
 f.close ()

Print file in ' Stray cat asleep in rocking swing ' after adding ' HelloWorld ' output

In R mode, we said to use for loops and readlines() output file content, this output is the principle of: Open the file, read all the content into memory, and then print input, when the file is very large, this reading method is not reliable, and even the machine crashes. We need to close the documents in time as follows:

f = open (' file ', ' R ')
Data=f.readlines ()  #注意及时关闭文件
f.close ()

num = 0 for
i in data:
  num = 1
  if num = = 5:
    i = '. Join ([I.strip (), ' Hello World ']) #不要使用 "+" for splicing
  print (I.strip ())
F.close ()

For large data files, use the following method:

num = 0
f.close ()  #不要过早关闭文件, otherwise the program does not recognize operation handle F.
f = open (' file ', ' R ') for I-in
f:  #for内部把f变为一个迭代器, row by row.
  num = 1
  If num = 5:
    i = '. Join ([I.strip (), ' Hello World '])
  print (I.strip ())
F.close ()

3.tell and Seek

Tell: the cursor position in the query file

Seek: Cursor positioning

f = open (' file ', ' R ')
print (F.tell ())  #光标默认在起始位置
f.seek    #把光标定位到第10个字符之后
print (F.tell ())  #输出10
f.close ()
----------------------
f = open (' File ', ' W ')
print (F.tell ())  #先清空内容, The cursor returns to
the 0 position f.seek    
print (F.tell ())
f.close ()
----------------------
f = open (' File ', ' a '
print (F.tell ())  #光标默认在最后位置 f.write (
' Hello World ')
print (F.tell ())  #光标向后9个字符, still in the last position
F.close ()

4.flush synchronization transfers data from cache to disk

example, implementing a progress bar feature

Import Sys,time  #导入sys和time模块 for
i in range:
  sys.stdout.write (' * ')
  Sys.stdout.flush ()  #flush的作用相当于照相, take a picture and flush a
  time.sleep (0.2)
The following code can also implement the same functionality import time for 
I in range (40):
  print (' * ', end= ', flush=true) #print中的flush参数
  time.sleep (0.2)

5.truncate truncation

cannot be performed in R mode,

In W mode, all data has been emptied and used truncate without any meaning,

In mode A, truncates the content after the specified position.

 f = open (' File ', ' a ')
 f.truncate (6) #只显示6个字节的内容 (6 English characters or three characters), and the following contents are emptied.

6. Summary of Cursor position

A Chinese character two bytes, involving the cursor position of the method has 4:,,, read tell seek truncate .

#--------------------------Cursor Summary head-----------------------------------
f = open (' file ', ' R ')
print ( F.read (6)) #6个字符
print (F.tell ())  #位置12字节, one kanji two bytes
f.close ()

f = open (' file ', ' R ')
F.seek ( 6)      #6个字节
print (F.tell ())
f.close ()

f = open (' File ', ' a ')
print (F.tell ())  #光标默认在最后位置
f.write (' Hello World ')
print (F.tell ())  #光标向后9个字节, a kanji two bytes, still in the last position 182-->191
f.close ()

f = Open (' File ', ' a ', encoding= ' utf-8 ')
print (F.truncate (6)) is #由于需要光标定位位置, so it is also byte. Displays only 6 bytes of content (6 English letters or three characters, two bytes of Chinese characters), and the following is emptied.
f.close ()
#-----------------------------Cursor Summary end---------------------------------

7. Another 3 modes: r+, w+, +

r+: Read and write mode, the cursor default in the starting position, when you need to write, the cursor automatically moved to the last

w+: Write read mode, first empty the original content, and then write, can also read

A +: Append read mode, the cursor default in the last position, write directly, also can read.

f = open (' File ', ' a ')
print (F.tell ())  #末尾207位置
f.close ()

f = open (' file ', ' r+ ')
print (F.tell ())  #0位置
Print (F.readline ()) #读取第一行
f.write (' Goat gazelle ')   #光标移到末尾207位置并写入
print (F.tell ())  # 213-bit
f.seek (0)     #光标移到0位置
print (F.readline ())  #读取第一行
f.close ()

8. Modify the contents of the file

Thinking: Due to the relationship between the data storage mechanism, we can only read the contents of file 1, after modification, put it in file 2.

F2 = open (' File2 ', ' W ', encoding= ' UTF8 ')  #写入的时候必须加utf8
f1 = open (' file ', ' r ')
num = 0 for line in
F1: #迭代器 C5/>num + + 1
  If num = 5: Line
    = '. Join ([Line.strip (), ' goat's '])  #里面就是对字符串进行操作了
  f2.write (line)
F1.close ()
f2.close ()

9.with statement

You can simultaneously operate on multiple files at the same time, when the with code block is finished, automatically closes the file to free memory resources, without specially adding f.close() , we use the following examples to understand with the usage and benefits.

withrewrite the code in 8 with the statement

num = 0
with open (' file ', ' R ') as F1,open (' File2 ', ' W ', encoding= ' UTF8 ') as F2: For line in
  F1:
    num = 1
    if num = = 5: Line
      = '. Join ([Line.strip (), ' goat Gazelle '])
    f2.write (line)

10. Summary

The above is the whole content of this article, hope to be helpful to everybody. If you have any questions, you can exchange messages

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.