How to use File objects in python Foundation
This article mainly explains "how to use the file objects in the foundation of python". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn how to use the file objects in the python foundation.
I. python reads and writes the contents of the file
Task: create a file named test.txt in the default login directory of cmd and write the content "welcome python"
Three steps to open a file
1. Create a file object-open the refrigerator door
two。 Read the file.-get the elephant out.
F = open ("C:\ Users\\ Administrator\\ test.txt", "rb") # 1f.read () # 2
F.seek (0.0) # flag bit returns to the start position before you can re-access # seek (offset to the right, start position) f.read (5) # read 5 bytes
3. Free up memory space-close the refrigerator door
F.close () II. Writing of file objects
1. Open the file.-Open the refrigerator door.
2 write file-put elephant
3. Save the file-close the refrigerator door
Request:
Create a file called testone in the user's home directory and write to
F=open ("C:\ Users\\ shiyan\ testone.txt", "wb") # rb is binary read wb is binary write f.writelines ([b "tom\ r\ n", b "jerry\ r\ n", b "bob\ r\ n"]) # multiple line write # f.wrtie () # single line write f.close 3, copy sf=open of file contents ("C:\ Users\\ shiyan\\ testone.txt") "rb") wf=open ("C:\ Users\\ shiyan\ testone.txt", "wb") data=sf.read () wf=write (data) sf.close () wf.close () 4. Copy the command line tool through the file object cmd.exe sf=open ("C:\ Users\\ shiyan\ cmd.exe", "rb") # write your own path wf=open ("C:\ Users\\ shiyan\\ dmc.exe" "wb") while True: data=sf.read (4096) # read 4096 bytes if data==b "": break wf=write (data) sf.close () wf.close () so far I believe you have a deeper understanding of "how to use file objects in the foundation of python", so you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!