Python Training Knowledge Summary Series-Chapter III Python3 file Operations (i)

Source: Internet
Author: User

Open

1
2
3
4
5
6
7
8
9
f = open (' filename ', ' R ') # Read mode
f = open (' filename ', ' W ') # Write mode
f = open (' filename ', ' a ') # Append mode

Note: RB is read in binary
Now you think it's useless, right, I think so.
But
In the future use of the socket, the transfer of files, read and write with the binary form
RB and WB can transfer files more quickly
  

Read content mode

F.read () # reads the entire file at a time, the file is not applicable
F.readline () # reads only one row at a time, which accounts for small memory and slow speed
F.readlines () # Once read, the content is parsed into a list of rows that can be for...in by ... Processing
How to write files

F.write (content) # It's not going to change.
F.writeline (content) # next time will be written on the next line
Close

F.close ()
Example:

f = open (' Cdays-4-test.txt ', ' R ') #以读方式打开文件
result = List ()
For line in F.readlines (): #依次读取每行
line = Line.strip () #去掉每行头尾空白
If not Len (line) or Line.startswith (' # '): #判断是否是空行或注释行
Continue #是的话, skip not processing
Result.append (line) #保存
Result.sort () #排序结果
F.close () #关闭文件
With open (' New_file.txt ', ' W ') as FW: #with方式不需要再进行close
Fw.write ('%s '% ' \ n '. Join (Result)) #保存入结果文件

Python Training Knowledge Summary Series-Chapter III Python3 file Operations (i)

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.