Python learning file manipulation;

Source: Internet
Author: User

File content Substitution
For line in Flielinput.input ("filepath", inplace=1):
line = Line.repace ("OldText", "NewText")
Print line,


The operation of files, folders (file manipulation functions) in Python involves both the OS module and the Shutil module.
1. Get the current working directory, which is the directory path of the current Python script work:OS.GETCWD ()
2. Return all files and directories under the specified directory name: Os.listdir ()
3. function to delete a file: Os.remove ()
4. Delete multiple directories: Os.removedirs (R ' C:\python ')
5. Verify that the given path is a file: Os.path.isfile ()
6. Verify that the given path is a directory: Os.path.isdir ()
7. Determine if it is an absolute path: Os.path.isabs ()
8. Verify that the given path is true: Os.path.exists ()
9. Returns the directory name and file name of a path: Os.path.split () eg
10.os.path.split ('/home/hczhang/finput.py ') results:
('/home/hczhang ', ' finput.py ')
11. Detach Extension: Os.path.splitext ()
12. Get path name: Os.path.dirname ()
13. Get File Name: Os.path.basename ()
14. Read and SET environment variables: os.getenv () and os.putenv ()
15. Give the line terminator used by the current platform: os.linesep Windows uses ' \ r \ n ', Linux uses ' \ n ' and Mac uses ' \ R '
16. Indicate the platform you are using: Os.name for Windows it is ' NT ', for Linux/unxi, it is ' POSIX '
17. Renaming: Os.rename (old,new)
18. Create a multilevel directory: Os.makedirs (r "C:\python\test")
19. Create a single directory: Os.mkdir ("Test")
20. Get File attributes: Os.stat (file)
21. Modify file permissions and timestamps: Os.chmod (file)
22. Terminate the current process: Os.exit ()
23. Get File Size: os.path.getsize (filename)
24. Using the command line under System: Os.system (' df-h ')

File operation:
1. Create empty file: Os.mknod ("Test.txt")
2. Open a file directly and create a file if the file does not exist: FP = open ("Test.txt", W)

About open mode:

W is opened in write mode;
A opens in Append mode (starting with EOF and creating a new file if necessary)
r+ Open in read/write mode;
w+ Open in read/write mode (W)
A + opens in read/write mode (parameter a)
RB opens in binary read mode;
WB opens in binary write mode (W)
AB opens in binary append mode (parameter a)
rb+ Ginseng r+
wb+ Ginseng w+
ab+ +


1.fp.read ([size]) #size为读取的长度, in bytes
2.fp.readline ([size]) #读一行, if size is defined, it is possible to return only a portion of a line:
3.fp.readlines ([size]) #把文件每一行作为一个list的一个成员 and returns the list;
In fact, it is internally through a loop called readline () to achieve, if the size parameter is provided, size is the total length of the read content, that is, may only be a part of the workshop;
4.fp.write (str) #把str写到文件中, write () does not add a newline character after Str;
5.fp.writelines (seq) #把seq的内容全部写到文件中 (multi-line write-once). This function is also a faithful write, and does not add anything behind each line;
6.fp.close () #关闭文件. Python will close the file after a file is not used, but this function is not guaranteed, it is best to develop their own closed habits. If a file is closed after the operation of it will produce valueerror;
7.fp.flush () #把缓冲区的内容写入硬盘: Save the file after the operation;
8.fp.fileno () #返回一个长整型的 "file label"
9.fp.isatty () #文件是否是一个终端设备文件 (on UNIX systems)
10.fp.tell () #返回文件操作标记的当前位置, starting with the origin of the file
11.fp.next () #返回下一行 and shifts the file action marker to the next line.
When a file is used for a statement such as for ... in file, the next () function is called to implement the traversal;

12.fp.seek (Offset[,whence]) #将文件操作标记移到offset的位置. This offset is generally calculated relative to the beginning of the file and is generally a positive number. However, if the whence parameter is provided, whence can be calculated as 0 for the start of the switch, and 1 for the current position as its origin. 2 means that the end of the file is calculated as the origin. Note that if the file is opened in a or a + mode, the file action tag is automatically returned to the end of the file each time the write operation occurs;
13.fp.truncate ([size]) #把文件裁成规定的大小, the default is to crop to the current file action tag location. If size is larger than the file, depending on the system, the file may not be changed, or the file may be added to the appropriate size with O, or it may be accompanied by some random content.



Directory Operations:
1. Os.mkdir (' file ') to create the directory;

To copy a file:
1.shutil.copyfile (' Oldfile ', ' newfile ') Oldfile and NewFile can only be documents;
2.shutil.copy ("Oldfile", "NewFile") Oldfile can only be a folder, NewFile can be a file, or it can be a destination directory

To copy a folder:
1.shutil.copytree ("Olddir", "Newdir") Olddir and Newdir can only be directories, and newdir must not exist;

Renaming files (directories)
Os.rename ("Oldname", "NewName")

Moving Files (directories)
Stutil.move ("Oldpos", "Newpos")

deleting files
Os.remove ("file")

Delete Directory
Os.redir ("dir") can only delete empty directories
Shutil.rmtree ("dir") empty directory, contents of the directory can be deleted

Converting catalogs
Os.chdir ("path") Change path



1. Seek (Offset,where) where=0 moves from the starting position, 1 moves from the current position, and 2 moves from the end position. When the current line breaks, it is truncated by wrapping.
Seek () return value, so the value is none;
2. Tell (): When the file position, that is, tell is to get the file pointer position, by seek, ReadLine, read, ReadLines influence, not affected by truncate;

3. Truncate (n): Truncate from the beginning of the first line of the file, truncate the file to n characters, no n indicates truncation from the current position, and after truncation all characters after n are deleted, where the line break of win represents 2 character size;

4. ReadLine (n); reads and puts a number of rows, n indicates the maximum number of bytes to be read and put. Where the read start position is tell () +1. When n is empty, the contents of the current line are read by default;




This article is from the "Seven" blog, make sure to keep this source http://sevenzhang.blog.51cto.com/429369/1568718

Python learning file manipulation;

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.