Python File processing Exercises

Source: Internet
Author: User

1, Analog CP command Copy file (image, video) to other paths

With open (' a.txt ', ' RB ')  as f,open (' B.txt ', ' WB ')  as write:         #选择rb模式, support all copies, the corresponding write mode is WB, directly processing is the bytes type         for  line in f:                                                                     #遍历源文件的每一行               write.write (line)                                                            #写入新文件write中 


However, this does not support the user to pass parameters, so the final code is as follows:

Import Sysif len (SYS.ARGV) <3: #用户输入参数少于3个 print (' Python3 copy.py source.file Targ Et.file ') #提示用户命令的用法需要3个参数 sys.exit () with open (R '%s '%sys.argv[1], ' RB ') as F,open (R '%s '%sys.argv[2], ' WB ') as Write : #这里处理的文件是基于用户输入的参数取到的 for line in F:write.write (line)


2, Python simulation tail command, display the contents of the log file, do not exit

Python3 tail.pyimport sysimport timewith open (R '%s '  %sys.argv[2], ' RB ')  as  Read:    read.seek (0,2)                              # The 2 pattern is referenced at the end, and the previous 0 represents the last byte, guaranteeing that the cursor is directly at the tail of the file     while True:         line=read.readline ()         if line:                                      #如果行有内容              print (Line.decode (' Utf-8 '), end= ')       #默认是字节码, converted to characters, end equals null indicates line breaks do not line up individually         else:        &nbSp;    time.sleep (0.2)                       #休息0.2 seconds to make a judgment.





Python File processing Exercises

Related Article

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.