Python Basic 09_ file operation

Source: Internet
Author: User

I. Basic procedures for file operations

#1. Open the file, get the file handle and assign a value to a variable f1=open (' B.txt ', ' R ', encoding= ' utf-8 ')
#2. manipulating files with a handle content=f1.read () print (content)
#3. Close File * * Always remember to add f1.close () 

Description: F1, file handle, file object.

Open (' File path '), default opening mode R, default open encoding is the default encoding for the operating system: Windows is GBK encoded, Linux and Mac default is Utf-8

Two. File encoding

Three. File Open mode

The mode of opening the file is:

    • R, read-only mode,
    • W, write-only mode, "unreadable, nonexistent, create, delete contents of file"
    • A, append mode, "unreadable, does not exist, is created, there is only append content"

"+" means you can read and write a file at the same time

    • r+
    • w+
    • A +

"B" means processing binary files

    • Rb
    • Wb
    • Ab

Four. How to read files

1.read

1) Read all the contents when the parameter is not passed. Note: When the file is large, it takes up a lot of memory and is not recommended for use.

2) The parameter refers to how many characters are read if it is opened in R mode.

3) If the parameter is open in RB mode, the transmission refers to how many bytes are read. such as network transmission \ Picture \ Video commonly used RB mode.

If there is a file A.log, the file content is

March Weather April Weather May Weather June Weather July Weather

Example 1: Open in R mode, read () reads all the contents of the file.

With open ("a.log", encoding="utf-8", mode="  R") as F:    content=f.read ()    print(content) Run Result: March Weather April Weather May Weather June weather July Weather

Example 2: Open in R mode, read (n), reads n characters

1 with open ("a.log", encoding="utf-8", mode="  R") as F:2     content=f.read (3)3      Print(content)45 Run Result:6 March

Example 3: Open in RB mode, read (n) reads n bytes

1 with open ("a.log", mode="RB") as F:2      Content=f.read (3)3     print(content)4  Running Result:5 b'\xe4\xb8\x89'

2.readline

Read one line at a time, not automatically stop

3.for Cycle

Read one line at a time, starting from the first line, and then stop after the supervisor has no

4.readlines

Five. Writing files

Write: Writes the content, the argument is a string

Writelines: Write content, parameter is List

Issues to be aware of:

1) w mode is on, character is written

2) WB mode Open, write bytes

3) does not wrap in the process of writing, you need to add a line break \ n

Example:

1With open (r"B.log", encoding="Utf-8", mode="W") as F:2F.write ("If Life deceives you,")3F.writelines (["If Life deceives you,","Don't be sad, don't be impatient","You need to be calm in a melancholy day .","believe it, the happy day will come! \ n"])

Write the contents of the file:

1 title: If Life deceives you 2 If Life deceives you, 3 Don't be sad, don't be impatient 4 I need to be calm in my melancholy days 5 believe it, the happy day will come!

Six. Modification of documents

Steps for Python to modify a file

1) Open the original file and generate a file handle
2) Create a new file, generate a file handle
3) Read the original file, modify it, write the new file
4) Delete the source file
5) Renaming new files
1 ImportOS2With open ("B.txt", encoding='Utf-8', mode="R") as F1,3Open"B.txt_bak", encoding="Utf-8", mode="W") as F2:4      forIinchF1:5New_content=i.replace (" China","Chinese")6 f2.write (new_content)7Os.remove ("B.txt")8Os.renames ("B.txt_bak","B.txt")

Six. Pointers in the file

    • Seek (): used to specify the position of the current pointer, which is the byte. Note in Utf-8 encoding, a Chinese character accounts for 3 bytes
    • Tell (): Indicates where the current pointer is located

Example:

1With open ("A.log", encoding="Utf-8", mode="R") as F:2F.seek (3)3Content=F.read ()4     Print(content)5     Print(F.tell ())6 Operation Result:7 months of Weather8 weather in April9 weather in MayTen weather in June One weather in July A73

If the Seek (3) in this example is changed to seek (2), the operation will be error, the reason Utf-8 encoded a Chinese character accounted for 3 bytes, if the pointer to the 2nd byte, Utf-8 decoding will be abnormal





Python Basic 09_ file operation

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.