Python file and directory operations detailed

Source: Internet
Author: User
I. Opening and creation of files

1. Open
Copy the Code code as follows:


Open (File,mode):

>>>FO = open (' Test.txt ', ' R ')
>>>fo.read ()
' Hello\n '
>>>fo.close ()
File (File,mode):

>>>f = File (' test.txt ', ' R ')
>>>f.read ()
' Hello\n '
>>>f.close ()


Mode desirable value:

2. Create

Open with w/w+/a/a+ mode.

Second, the file read
1, String = Fileobject.read ([size])
Copy the Code code as follows:


>>> fr = open (' Test.txt ')
>>> Fr.read ()
' Hello\nworld\n '


Or
Copy CodeThe code is as follows:


>>> for I in open (' Test.txt '):
... print I
...
Hello

World


2, String = Fileobject.readline ([size])
Copy CodeThe code is as follows:


>>> f = open (' Test.txt ')
>>> F.readline ()
' Hello\n '
>>> F.readline ()
' World\n '
>>> F.readline ()
''


Or you can use next

3. List = Fileobject.readlines ([size])
Copy the Code code as follows:


>>> f = open (' Test.txt ')
>>> F.readlines ()
[' hello\n ', ' world\n ']

Iii. Writing of files

1. Write (String)

Copy the Code code as follows:


>>> f = open (' Test.txt ', ' a ')
>>> f.write (' Hello\nworld ')

# ' Hello\nworld '

2. Writelines (list)

Copy the Code code as follows:


>>> L = [' A ', ' B ', ' C ']
>>> f=open (' test.txt ', ' a ')
>>> F.writelines (L)

# ' HELLO\NWORLDABC '


Note: Writelines is equivalent to calling multiple write and does not automatically add line break (\ n) characters

Iv. content Search and replace

1, Fileobject.seek (offset, mode)

Offset: Offsets

Mode
0 means pointing the file pointer from the file header to the "offset" byte,
1 means pointing the file pointer backwards from the file's current position to the "offset" byte,
2 indicates that the file pointer is directed to move the offset byte forward from the end of the file.

Copy the Code code as follows:


>>> f=open (' Test.txt ')
>>> F.read ()
' Hello\nworldabc '
>>> F.read ()
''
>>> F.seek (0,0)
>>> F.read ()
' Hello\nworldabc '
>>> F.close ()

2, Flush: Commit the update, that is, before the file is closed, the contents of the memory is forced to write to the file (usually the file is closed after writing)

3. File Lookup: Traverse rows for Lookup
Copy the Code code as follows:


#!/usr/bin/python
Import re

Search= ' Hello World '
File= ' Test.txt '
Count = 0
f = open (file)
For L in F.readlines ():
Li = Re.findall (search,l)
If Len (LI) > 0:
Count + = Len (li)
Print "Search" + str (count) + "\" "+ Search +" \ ""
F.close ()

4, File content substitution: Traverse line to replace

Replace to new file demo:
Copy the Code code as follows:


#!/usr/bin/python

os= ' Hello '
of= ' Test.txt '

Rs= ' Ten '
rf= ' Test2.txt '

OFH = open (OF)
Newl=[]
For L in Ofh.readlines ():
NL = L.replace (OS,RS)
Newl.append (NL)

RFH = open (RF, ' w+ ')
Rfh.writelines (NEWL)
Ofh.close ()
Rfh.close ()


Replace to original file demo:
Copy CodeThe code is as follows:


[Server@localserver file]$ Cat Test.txt
Abc
Hello
World
Hello World
HelloWorld
Hello Hello World
[Server@localserver file]$ Cat fr.py
#!/usr/bin/python

os= ' Hello '
File= ' Test.txt '

Rs= ' Ten '

f = open (file, ' r+ ')
S=f.read ()
F.seek (0,0)
F.close ()
f = open (file, ' w+ ')
F.write (S.replace (OS,RS))
F.close ()
[server@localserver file] python fr.py
[Server@localserver file]$ Cat Test.txt
Abc
Ten
World
Ten World
Tenworld
Ten ten World

The method of rebuilding the file was adopted here.

or modify the original file directly with the Fileinput module:
Copy the Code code as follows:


#!/usr/bin/python
Import Fileinput

os= ' Hello '
File= ' Test.txt '

Rs= ' Ten '

For line in Fileinput.input (file, inplace=true):
Print Line.replace (os,rs). replace (' \ n ', ')


Note that \ n is removed because print is written as a newline.

V. File and directory Operations

Typically, the OS module implements

1, mkdir (path[,mode=0777]): Create a directory, equivalent to mkdir
Copy the Code code as follows:


>>>import OS
>>>os.mkdir (' TT ')


2, Makedirs (name[, mode=511]): Create a multilevel directory, equivalent to Mkdir-p

3, RmDir (path): Delete directory, equivalent to RM

4, Removedirs (path): Delete the multilevel directory, equivalent to RM-RF

5, Listdir (path): List files and folders in the directory, equivalent to LS

6, GETCWD (): Gets the current path, equivalent to PWD

7, ChDir (PATH): Switch directory, equivalent to CD

8. Rename (src, DST): renaming

9, Shutil.copyfile (STR,DST): Copy file (to introduce Shutil module)

10. Path.splitext (filename): Get file path and extension
Copy the Code code as follows:


>>> Import OS
>>> fileName, fileextension = Os.path.splitext ('/path/to/somefile.ext ')
>>> FileName
'/path/to/somefile '
>>> fileextension
'. Ext '

11, Walk (top, Topdown=true, Onerror=none): Traverse directory
Copy the Code code as follows:


>>> Import OS
>>> g = Os.walk (' a ')
>>> G.next ()
(' A ', [' B '], [])
>>> G.next ()
(' A/b ', [' F ', ' C '], [])
>>> G.next ()
(' a/b/f ', [], [' 3.txt '])
>>> G.next ()
(' a/b/c ', [' d ', ' e '], [])
>>> G.next ()
(' a/b/c/d ', [], [' 1.txt '])
>>> G.next ()
(' a/b/c/e ', [], [' 2.txt '])


Walk returns a generator in which the contents of the generator are: current directory, directory list, file list

Python recursively implements file traversal:
Copy the Code code as follows:


#!/usr/bin/python
Import OS

def dirlist (path):
filelist = Os.listdir (path)
Fpath = OS.GETCWD ()
Allfile = []
For filename in filelist:
filepath = Os.path.abspath (os.path.join (path, filename))
If Os.path.isdir (filepath):
Allfile.extend (Dirlist (filepath))
Else
Allfile.append (filepath)
Return Allfile

Files = dirlist (' a ')
Print files

  • 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.