#Also known as IO stream, it is divided into two directions : reading files and writing files. #Reading files: inputstream input stream, reads the files on the disk into the program for processing (in memory) #Write files: outputstream output stream, transfers the files into the program The file is written to the disk #File reading and writing, that is, the exchange data between disk and memory #Memory: It saves temporary data when the program is running, and it will be cleared when the program is closed #Disk: It stores permanent data #File classification : 1. Text file: also called character file, which only saves text documents of strings, such as .txt/json/css, etc. #2. Binary file: also called byte file, which can save multimedia data in any format . For example: picture/audio/video/word/excel #File operation steps: open read close #1. Read the fileaaa ="C:\\Users\\yahui.zhao\\Desktop\\aaa.txt"#Don't Forgot to cancel the translation file=open("C:\\Users\\yahui.zhao\\Desktop\\aaa.txt", "r")#open (file path name, access mode) r--read file #Must not Forgot the double quotes of r data=file.read()#Read the file file.close()#Close the file print(data) print(type(data))#The text is a string document # 2. Write the file s= "Hello a, Shanghai" file=open(aaa,"w")#"w", if the file does not exist, create a new file, if the file exists, overwrite the original file, the file path must actually exist file.write(s) file.close() # Close File xixi="Haha, it's not overwritten" file=open(aaa,"a")#"a" is not overwritten and directly writes file.write(xixi) file=open(aaa,"r") data=file. read() file.close()#Close the file print(data) #Text file: r,w,a #Binary file: rb,wb,ab file=open(r"C:\Users\user\Desktop\Enterprise WeChat Screenshot_16557208021155.png","rb") data=file.read() file.close( ) file1=open(r"C:\Users\user\Desktop\1155.png","wb") file1.write (data) file1.close() file1=open(r"C:\Users\user\Desktop\1155.png","rb") data=file1.read() print(data) #Using the above method, we often forget to close the file, which leads to higher-order methods. with open("C:\\Users\\yahui.zhao\\Desktop\\666.txt","r",encoding="utf-8") as file2,open("C:\\Users\\yahui .zhao\\Desktop\\aaa666.txt","w",encoding="utf-8") as file3: data=file2.read() file3.write(data) #Note: write can only write string types, not dict, list and other types.
Python basic syntax--file reading and writing
Guess you like
Origin blog.csdn.net/qq_40333984/article/details/125501474
Recommended
Ranking