Python modifies the file content without the need to read or write multiple actions .,

Source: Internet
Author: User

Python modifies the file content without the need to read or write multiple actions .,

Python is usually used to read, write, and rename the file content to be modified.

For example, you need to set yuv_dir = "../HD/" #"H:/HD_Master/1080i25 /"

Changed to yuv_dir = "C:/HD/" #"H:/HD_Master/1080i25 /"



It is very simple, but it is not easy to operate, because after reading the file pointer to the next line, it is difficult to use seek to the first line.



Many applications usually need to process files, but there is a fixed mode for processing files: open the file, read some data, process the data, print it to the screen or write it into another file.

So what should we do if we want to write back the file immediately after modification? In what mode? How can I read and write data?

I personally tried a lot of methods, either unable to implement or very difficult to operate. Eventually give up.

Fortunately, the Python built-in module fileinput can be easily completed. The Code is as follows:


For line in fileinput. input ("case_20.gaoqing.py", inplace = 1 ):
Line = line. replace ("...", "C :")
Print line,

In this way, the goal is achieved, which is very simple.


For more information about fileinput, http://docs.python.org/library/fileinput.html here





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.