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