Python Basics Supplement

Source: Internet
Author: User

One, the file operation

Open () #打开文件

Open (' A.txt ', ' W ', encoding= ' utf-8 ') #防止乱码

R, a, w--read only, append write, write only three modes

u# change the line breaks in all the files to \ n

b# binary operation

The. Read () #读文件

. ReadLine () #读取一行, a row of read files

. ReadLines () #读文件的全部内容, the return is a list

For line in F:

Print (line) #循环读取文件每行内容, recommend this method

The. Write () #写

. Wrielines () #写一个list

. Seek (0) #指定文件指针位置

. Tell () #读文件

. Truncate () #清空

. Close () #关闭文件

. Flush () #缓冲区的文件立即生效

With open (' A.txt ', ' R ') as fw,\ #一行代码写不完可以加一个 \ Connects two lines of code; Use with to write no more. Close

Open (' B.txt ', ' W ', encoding= ' Utf-8 '):

Src_res=fw.read ()

Res=src_res.replace (' xxx ', ' DSSSD ') #替换

Fw.write (res) #如果要修改原文件, you must create a new file and write the modified contents of the original file into the new file.

Os.remove (' A.txt ')

Os.rename (' B.txt ', ' a.txt ') #把原文件删除, rename the new file to the original file

Python Basics Supplement

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.