directory

  • Open the Python file
  • Close the Python file
  • 3. Read Python files
    • 1. Read function
    • 2. Readline function
    • 3. The readlines function
  • Write to Python files
    • 1. Write function syntax
    • 2. Write function use case
  • Python file offset seek
    • 1. The seek function
    • 2. Tell the function
    • 3. Seek/tell function example generation…
  • Six. Key summary
  • Seven. Guess you like it

Recommended path for learning Python: Python Learning Directory >> Python Basics

In addition to printing data to the console through the print function, Python can also read/write data to disk files. File reading and writing is short for I/O operations. Python file I/O operations are divided into four parts:

  • Open (open)
  • Read (read)
  • Write (write)
  • Closed (close)

Open the Python file

To open a file in Python, use the function open, which returns a handle to the file as follows:

File = open(" file name "," open file mode ") TXT file = open("d:/1.txt","wb");Copy the code

The file opening mode has the following types:

Close the Python file

After opening and reading files, remember to have a close operation. It is like wiping your ass after squatting. Close files using the close function.

Note: After the file is closed, you cannot continue reading or writing the file. If you need to read or write the file, you need to open the file again.

Close () # Close the fileCopy the code

3. Read Python files

After the file is opened, the contents of the file can be read using the returned file handle. There are several functions for file reading:

1. Read function

Conut is the default. If count is not set, the entire file is read by default. This function returns what is read. Return value: Returns what was read; Instead of a string STR, the file read returns bytes, which are represented by the 'b' prefix. "" read([count])Copy the code

2.readlinefunction

Readline ()Copy the code

3.readlinesfunction

Readlines (); // Readlines (); // Readlines ();Copy the code

** Note: the file read does not return the string STR, but bytes. The ‘b’ prefix represents bytes. **

** To convert bytes to a string, use the bytes.decode method, which uses utF-8 encoding by default; ** If the contents of d:/1.txt are as follows:

@blog (personal Blog address): www.codersrc.com @Motto: No accumulation of small steps no thousands of miles, no accumulation of small streams no rivers and seas, the wonderful life of the program needs unremitting accumulation!Copy the code

Sample code for three ways to read a file is as follows:

#! Usr /bin/env python # -* -coding :utf-8 _*- "" www.codersrc.com @file :Python File read and write operation. Py @time :2021/04/17 10:00 @Motto: No accumulation of small steps to a thousand miles, no accumulation of small streams into rivers and oceans, the wonderful life of the program needs unremitting accumulation! "" # print(" ") file_object = open("d:/1.txt","rb") contents = file_object.read() Print ("-- "*20) print("-- "*20) Print (" decode() ") print(contents. Decode ()) file_object.close() print("***"*20) ") file_object = open("d:/1.txt","rb") while True: Contents = file_object.readline() print(contents. Decode ()) Break file_object.close() print("***"*20) ") file_object = open("d:/1.txt","rb") # readlines() returns the list, Contents = file_object.readlines() # iterate over the list for content in contents: Print (content.decode()) print(content.decode()) print(content.decode()) B '@blog (\xe4\ XB8 \xaa\xe4\xba\xba\xe5\x8d\x9a\ xae\xa2\xe5\x9c\ XB0 \xe5\x9d\x80): www.codersrc.com\r\n@WeChat Official Account(\xe5\xbe\xae\xe4\xbf\xa1\xe5\x85\xac\xe4\xbc\x97\xe5\x8f\xb7)\xef\xbc\x9a\xe7\x8c\xbf\xe8\xaf\xb4python\r\n@Mott o:\xe4\xb8\x8d\xe7\xa7\xaf\xe8\xb7\xac\xe6\xad\xa5\xe6\x97\xa0\xe4\xbb\xa5\xe8\x87\xb3\xe5\x8d\x83\xe9\x87\x8c\xef\xbc\x 8c\xe4\xb8\x8d\xe7\xa7\xaf\xe5\xb0\x8f\xe6\xb5\x81\xe6\x97\xa0\xe4\xbb\xa5\xe6\x88\x90\xe6\xb1\x9f\xe6\xb5\xb7\xef\xbc\x 8c\xe7\xa8\x8b\xe5\xba\x8f\xe4\xba\xba\xe7\x94\x9f\xe7\x9a\x84\xe7\xb2\xbe\xe5\xbd\xa9\xe9\x9c\x80\xe8\xa6\x81\xe5\x9d\x 9a\xe6\x8c\x81\xe4\xb8\x8d\xe6\x87\x88\xe5\x9c\xb0\xe7\xa7\xaf\xe7\xb4\xaf\xef\xbc\x81\r\n' -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- use the decode () function to decode English: @ Blog (personal Blog address) : www.codersrc.com @Motto: No longer a thousand miles, no longer a small stream, no longer a river or sea, the wonderful life of the program needs unremitting accumulation! * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * method 2: use readline () function to read TXT @ Blog content (personal Blog address) : www.codersrc.com @Motto: No longer a thousand miles, no longer a small stream, no longer a river or sea, the wonderful life of the program needs unremitting accumulation! * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * method 3: using readlines () function to read TXT @ Blog content (personal Blog address) : www.codersrc.com @Motto: No longer a thousand miles, no longer a small stream, no longer a river or sea, the wonderful life of the program needs unremitting accumulation! ' ' 'Copy the code

Write to Python files

1. Write function syntax

File writing can be done by using the write function, which is easy to use.

Write ([bytes]); // Write ([bytes]);Copy the code

2. Write function use case

#! Usr /bin/env python # -* -coding :utf-8 _*- "" www.codersrc.com @file :Python File read and write operation. Py @time :2021/04/17 10:00 @Motto: No accumulation of small steps to a thousand miles, no accumulation of small streams into rivers and oceans, the wonderful life of the program needs unremitting accumulation! "" "file_object = open (" d: / 2. TXT ", "wb") # '\ n' is the newline character in the file I/O, after finished the file, Write (b"1234567\n") # Note the use of file_object.write(b"file_object.write(b'sad')\n") File_object.write (b"python \n") file_object.close() "" d:/2.txt  1234567 file_object.write(b'sad') python '''Copy the code

Note: the writing mode is’ WB ‘, each time the file is written, the last content will be overwritten, that is, the content before writing will be emptied;

Python file offset seek

Those who have looked at the sample code for the read function above might think that opening and closing files frequently is a bit of a hassle. Then only open and close the file once, through the file offset can also be done, file offset using the ** seek** function. In general, seek and tell functions are used together;

1. The seek function

Parameter: offset - indicates the number of bytes offset relative to whence; whence - indicates the offset position, 0 from the beginning of the file, 1 from the current position, 2 from the end of the file; ''' seek([offset],[whence])Copy the code

2. Tell the function

// The number of bytes currently offset from the start of the file seek([offset],[whence])Copy the code

Tip: The tell function can also be used to calculate the bytes length of the entire file;

3. Seek/tell function sample code

#! Usr /bin/env python # -* -coding :utf-8 _*- "" www.codersrc.com @file :Python File read and write operation. Py @time :2021/04/17 10:00 @Motto: No accumulation of small steps to a thousand miles, no accumulation of small streams into rivers and oceans, the wonderful life of the program needs unremitting accumulation! "" file_object = open("d:/2.txt","rb") Count = file_object.tell() print(count) Contents = file_object.read() # Print (count) # print(count) # print(count) # File_object.seek (0,0) Contents = file_object.readline() print(contents. Decode ()) Contents = file_object.readline() print(contents. Decode ()) Print (count) file_object.close() "" : 0 474 Python tutorial www.codersrc.com 68 Python tutorial - Python tutorial: Second row of data www.codersrc.com 136 ""Copy the code

Note: The file pointer is offset automatically by calling read/readline/readlines/write.

Six. Key summary

  • 1. The read function can be set to read a specified length, for example, only 10 characters read(10);
  • 2. Readlines returns a list, not bytes, in which each element is a row of data in a file of type bytes.
  • 3. If the file contains Chinese characters, decode the file into a string using the decode function, which uses UTF-8 decoding by default.
  • 4. Remember close after open to develop good writing habits;

Seven.Guess you like

  1. The Python for loop
  2. The Python string
  3. The Python list
  4. The Python tuple tuple
  5. Python dictionary dict
  6. Python conditional derivations
  7. Python list derivations
  8. Python dictionary derivations
  9. Python function declarations and calls
  10. Python variable argument *argc/**kargcs
  11. Python anonymous function lambda
  12. Python return logic determines expressions
  13. Python string/list/tuple/dictionary conversions
  14. Python local and global variables
  15. The Python type function is different from the isinstance function
  16. Python is differs from ==
  17. Python mutable and immutable data types
  18. Shallow and deep copies of Python

Read and write Python files

This article is published by the blog – Ape Say Programming Ape Say programming!