Learn to write: Python file open, write, copy

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.