Python basics 4: file operations,

Source: Internet
Author: User

Python basics 4: file operations,

File knowledge: open files, operate files, and close files


1. about opening a file:

F. open ('text', 'R') # r indicates read-only
F. open ('text', 'w') # w indicates writing only. Clear the source file content first.
F. open ('text', 'x') # If the file exists, an error is returned. If the file does not exist, the file is created and the content can be written (w)
F. open ('text', 'A') # a indicates appending content to the end of the source file

Case 1: Program for reading file content

f=open('db','r')
data=f.read()
print(data)
f.close()

Case 2: encoding limits the file content format

# Read the file content. If garbled characters occur when opening the file, check whether the corresponding encoding type is true or not.
# For example, if the text file contains Chinese characters, you must enter encoding = 'utf-8'
F = open ('text', 'R', encoding = 'utf-8 ')
Data = f. read ()
Print (data)
F. close ()

Case 3: After adding B, the file is read in byte mode. If not, the file is read as a string.

F = open ('db', 'rb') # When r is rb, the file is read in bytes.
Data = f. read ()
Print (data, type (data ))
F. close ()

Case 4: When the transmitted content is a character, it needs to be converted by bytes

F = open ('db', 'AB') # It is appended in bytes.
F. write (bytes ("hello", encoding = 'utf-8') # Use bytes to convert the transmitted content to a character.
F. close ()

Case 5: r + can be read and writable without overwriting the file. content will be appended at the end.

F = open ('db', 'r + ', encoding = 'utf-8') # Read and Write
Data = f. read ()
Print (data)
F. write ("hello") # overwrite at the end
F. close ()

Execution result:

In addition, there is a + (implement read and write, but the write will always be appended at the end), w + (implement write and read, but will clear the source file content and write ), therefore, r + is the most used


2. File Operations

Seek () # Read the pointer position in byte format. The Chinese Character represents three bytes.
Tell () # obtain the position of the current pointer in bytes

Case 6: Adjust the pointer position

F = open ('db', 'r + ', encoding = 'utf-8') # Read and Write
Data = f. read (1) # If Model B is enabled, read reads by character. If Model B is enabled, read by byte. For example, Chinese occupies three bytes.
Print (f. tell () # position of the current tell () pointer, in byte format, no matter whether there is B
F. seek (f. tell () # You can adjust the position of the current pointer.
F. Writes ("888 ")
F. close ()

Case 7: flush # Strong click. When the program is not finished, you need to force write content into the memory.

F = open ('db', 'A ')
F. Writes ("123 ")
F. flush () # forcibly write 123 of the content to the hard disk
Input ("hhh ")

Case 8: truncate, used to truncate data

F = open ('db', 'r + ', encoding = 'utf-8') # Read and Write
F. seek (3) # adjust to 3 bytes
F. truncate () # All content after 3 bytes is cleared
F. close ()

Others: readline. Only one row is read.


3. close the file

You can use f. close () or use with to automatically close

with open('db') as f:
input("hhh")

Case 9: Read the previous row of the first file and write it to the second file

With open ('db', 'R') as f1, open ('db2 ', 'w') as f2:
Times = 0
For line in f1: # read data from one row
Times + = 1
If times <= 10: # control times
F2.write (line)
Else:
Break

Case 10: modify a file and replace some content

with open('db','r')as f1,open('db2','w')as f2:
for line in f1:
new_str=line.replace("aaa","cc")
f2.write(new_str)


Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.