Python file operations

Source: Internet
Author: User

Read and write files
f = open ("Test.txt","R", encoding='Utf-8') data = F.read ()
Print (data) F= Open ("Test.txt","W", encoding='Utf-8'#写入, is the way to create new files, and if there are duplicate names of the files, the old content will be emptied. F.write ("hehe \ n") #\n is a newline character.
F.close () #关闭文件
Append file
f = open ("test.txt","a", encoding='utf-8 ' ) f.write (" oh da ") f.close ()
Read file by line
 #   Cheng  f = open ( " test.txt  " ,  " r  " , Encoding= '  
f = open ("test.txt","R", encoding='utf-8 ' ) for in range (5): #读五行     print(F.readline ()) F.close ( )

Another way ReadLines

First, look at what the ReadLines output looks like.

It will convert the contents of the file into a list.

Next we output what we want.

#the writing of Cheng rubbishf = open ("Test.txt","R", encoding='Utf-8') Count=0 forLineinchf.readlines ():ifCount <= 9:#Remove the first 10 lines        Print(Line.strip ()) Count+ = 1Else: Exit () F.close ()

Note: It's OK to read a small file so that reading a large file requires the file to be stored in memory, which causes the program to die.

Advanced Notation (iterator) #

#Chengf = open ("Test.txt","R", encoding='Utf-8') Count=0 forLineinchF:#because the file pointer does not go backwards, it is also progressive.     ifCount <= 9:        Print(line) Count+ = 1Else: Exit () F.close ()

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.