Python uses the open () function to open the file return object:
Open second parameter
| "R" |
Open a file as read-only |
| "W" |
Open file in Write method, overwrite stored content |
| "X" |
Open throws an exception if the file is present |
| A |
Opens the file in write mode and, if it exists, adds the file at the end |
| "B" |
Open a file in binary mode |
| "T" |
Open a file in text mode (default) |
| "+" |
Read/write mode (can be added to other modes) |
| U |
Universal Line break support |
Methods for file objects :
| Close () |
Close File |
| Read (Size=-1) |
Reads a size character from a file, reads all remaining characters when not given a size or a given negative value, and then returns the string back as a character |
| ReadLine () |
Reads a whole line of string from a file |
| Write (str) |
Writes the string str to the file |
| Writelines (seq) |
To write a string sequence to a file seq,seq should be an iterative object that returns a string |
| Seek (Offset,from) |
Move the file pointer in the file, from the from (0 for the file start position, 1, for the current position, 2 for the end of the file) offset by offsets bytes |
| Tell () |
Returns the current position in the file |
Read and locate the file:
1>>>f=open ("d:/text File/1.txt")2>>>F.read ()3 'Hello, friends \nhello friend'4>>>F.tell ()5246>>>f.seek (0,0)#set the file pointer to the starting position7 08>>>f.read (5)#read 5 bytes per byte9 'Hello, friend.' Ten One>>> F.readline ()#reads a line (that is, from the text pointer to \ n) A 'Hello, friend \ n'
13
14
>>>f.seek (0,0)
>>>for Each_line in F:
Print (Each_line) #使用迭代来返回每一行文本
Write to File:
If you write to a file, make sure that you open it in "w" or "a" mode, and then tune the writer () function
1 f=open ("d:/text file/1.txt", "w")23 f.write (" Hello everyone ")45 f.close ()
Actual combat:
Python file Write and save