Python uses OS modules and Fileinput modules to manipulate file directories

Source: Internet
Author: User
OS Module
In Python programming, we often use files and directories, which Python provides an OS module with many functions for manipulating files and directories.

The following describes the common features of the OS

1. Get the current path

>>> os.getcwd () '/root/python '

2. Get content in a directory

>>> Os.listdir (OS.GETCWD ()) [' deco.py ', ' 6.py ', ' inputfile.py ', ' unifile.py ', ' oddnogen.py ', ' ospathex.py ', ' operate.py ', ' bianliang.py ', ' typecheck1.py ']

3. Create a Directory

>>> os.mkdir ('/root/pythontest ')

Create a nested directory once can use Os.makedirs,makedirs can generate multi-level recursive directory, removedirs can delete the multi-level recursive empty directory, if there are files in the directory can not be deleted; Os.system (): Run the shell command;

>>> os.environ[' home '/root ' >>> os.makedirs (os.path.join (os.environ[' home '], ' test ', ' py ')) > >> os.system (' ls-lr/root/test ')/root/test:total 4drwxr-xr-x 2 root root 4096 2013-03-29 17:27 Py/root/test/py:tot Al 00

4. Change the working directory

>>> os.getcwd () '/root/python ' >>> os.chdir (' etc ') >>> os.getcwd () ' etc '

5. Deleting a directory

>>> os.rmdir ('/root/pythontest ') >>>

Note: Deleting a directory must be an empty directory

6. deleting files

>>> os.remove ('/root/pytest.py ')

7. renaming files or directories

>>> os.rename ('/root/pytest.py ', '/root/test.py ')

8. The string gives the terminator used by the current platform, for example: Windows uses ' \ r \ n ', Linux uses ' \ n '

>>> os.linesep ' \ n '

The following is the Os.path module

9. Determine if it is a directory

>>> os.path.isdir ('/root/python ') True

10. Determine if the file is

>>> os.path.isfile ('/root/python ') False

11. Returns the directory name and file name of a path

>>> Os.path.split (OS.GETCWD ()) ('/root ', ' python ')

12. Determine if a file or directory exists name

>>> os.path.exists ('/root ') true>>> os.path.exists ('/root/1.py ') False

13. Get File Size

>>> os.path.getsize ('/root/python/if.py ') 282

14. Return file path, return filename

>>> os.path.dirname ('/root/python/if.py ') '/root/python ' >>> os.path.basename ('/root/python/ if.py ') ' if.py '

15. Connect the directory with the file name or directory

>>> os.path.join ('/dave/test/', ' 1.py ') '/dave/test/1.py '

Determine which files are in a directory and which are directories.

>>> for file in Os.listdir ('/root/python '): ...   If Os.path.isdir (file): ...     Print file, "is a directory"   ... else:     ... Print file, "is a file" ... deco.py is a fileinputfile.py are a fileoperate.py is a filehello.pyc are a fileuserpw.py is a fil E4.py is a fileanswer is a directory

Fileinput Module
The Fileinput module can traverse all lines of a text file. It works like a readlines, except that it does not read all the rows to the list but creates a Xreadlines object.

The following are common functions in the Fileinput module

    • Input () #它会返回能够用于for循环遍历的对象.
    • FileName () #返回当前文件的名称
    • Lineno () #返回当前 (cumulative) Number of rows
    • Filelineno () #返回当前文件的行数
    • Isfirstline () #检查当前行是否是文件的第一行
    • Close () #关闭序列
>>> import fileinput>>> for eachline in Fileinput.input ("/root/datafile.txt"): ...   Print Eachline ... Dave python >>> for eachline in Fileinput.input ("/root/datafile.txt"): ...   Print Fileinput.filename () .../root/datafile.txt/root/datafile.txt>>> for eachline in Fileinput.input ("/ Root/datafile.txt "):   ... Print Fileinput.lineno (), eachline ... 1 Dave 2 python >>> for eachline in Fileinput.input ("/root/datafile.txt"): ...   If Fileinput.isfirstline (): ...     Print Eachline   ... else:     ... Break ... Dave

Here is a small instance of log analysis that intercepts matching phone numbers in the log, such as 800-333-1212

root@10.1.1.45:~# cat Telphone.log 027-987-121202187899682021-110-9632root@10.1.1.45:~# cat fileinputtest.py #!/usr/ bin/python2.5 Import Fileinputimport sysimport Re pattern = "\d{3}-\d{3}-\d{4}" FilePath = "/root/telphone.log" for Eachli NE in Fileinput.input (filePath):  a = Re.search (pattern,eachline)  if a:#    sys.stdout.write ("============\ n ") #    Sys.stdout.write (eachline)     print" ============ "     print ' line: ', Fileinput.lineno (), ' filename: ', Fileinput.filename (), ' Length: ', Len (Eachline.strip (' \ n ')), eachlineroot@10.1.1.45:~#./fileinputtest.py ==========  ==line:1 filename:/root/telphone.log length:12 027-987-1212 ============line:3 filename:/root/telphone.log length:12 021-110-9632
  • 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.