Variable =open ("file to open", open mode)
There are three ways to open, read, write, execute, default open mode for reading, if written, if the file exists, then empty all content, if not, create a new file, such as
f = open ("/bin/ls")//quotation marks for filenames, not variables
F.read ()//is empty in parentheses, indicating that all of the files are read out, with a few brackets indicating "read on Demand" in bytes
F.readline (size)//read a line of the file
F.readlines (["File contents \ n", "File contents \ n"])//To read all the lines in the file and put them in the list
F.write ("Hello,world!!!") The Hello,world!!! Write to the file.
F.writelines (["hello\n", "world\n"])//list can be written to multiple lines, need to add \ n to break the line
F.flush ()//If you need to write it right away, you need to execute this command, which is equivalent to ctrl+s saved in Word
F.close ()//Close the file, the content added after closing the file will be written on the disk, when it is greater than 4096 bytes, it will be automatically written to the hard disk, will not always reside in memory.
[Email protected] python]# vim cp.py
#!/usr/bin/env python
S_fname = "/bin/ls"//assigns the file name to the variable
D_fname = "/root/haha"
S_fobj = open (s_fname)//Open file and copy to variable
D_fobj = open (D_fname, "w")
Buf_size = 4096
While True:
data = S_fobj.read (buf_size)//read 4,096 bytes to data
If not data://If data is empty, break to end this program
Break
D_fobj.write (data)//write data to the target file
This article is from the "Court of the Odd Tree" blog, please be sure to keep this source http://zhangdl.blog.51cto.com/11050780/1827760
Learn to write: Python file open, write, copy