Python file operations

Source: Internet
Author: User

There are two ways in which Python operates files:
The first type:
Money = open (' Wages.txt ', ' R ', encoding= ' utf-8 ')
Your_money = Money.readline ()
Money.close ()
Note that you need to shut down after opening, otherwise occupy memory.
Some of the most common things
The second argument after open:
R Read Only #
W Write only #
A append write, plus the + number, is read and write, read, add read and write
u# change the line characters in all the files to \ n
b# binary

#读取文件的三种模式
The. Read () #读取文件的所有内容, which returns a string
. ReadLines () #读取文件的所有内容, a list is returned, and the contents of each row are an element of the list
. ReadLine () #读一行
For I in F:
Print (i)

The. Write () #写一个字符串
. Writelines () #写一个list

Other ways to use:
. Seek () #移动文件的指针到xx位置
. Tell () #查看文件当前的指针在哪里
. Truncate () #清空文件
. Close () #关闭文件
. Flush () #立即把内存里面的数据写到文件里面

The second type:

With open (' Wages.txt ', ' W ', encoding= ' Utf-8 ') as M:
M.write (str (Your_money))

This does not require the file to be closed

The second bit parameter is the same as the first way:

To modify the contents of a file:

If you want to modify the original file, you must create a new file, the source file to write the modified value of the new file
Os.remove (' A.txt ')
Os.rename (' A.txt.bak ', ' a.txt ')

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.