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