Python file read-write and file directory and folder operations

Source: Internet
Author: User
Tags posix python script

For security reasons, it's a good idea to specify a name for the open file object so that you can close the file quickly after the operation is complete, preventing some useless file objects from taking up memory. For example, read from a text file:
File_object = open (' Thefile.txt ')
Try
All_the_text = File_object.read ()
Finally

File_object.close ()


Five steps to actual operation of Python read and write files

First, open the file

Python read and write files in the computer language is widely used, if you want to know the application of the program, the following article will give you a detailed introduction of the relevant content, you will be helpful in the process of learning later, we will detail its application.
The code is as follows:

 
   
  
  1. F  =  Open ("D:\test.txt", "W")

Description

The first parameter is the file name, including the path, and the second argument is the open mode
' R ': Read-only (default. Throws an error if the file does not exist)
' W ': Write-only (if the file does not exist, the file is created automatically)
' A ': Append to end of file
' r+ ': Read and Write
If you need to open the file in binary mode, you need to add the character "B" after mode, such as "RB", "WB", etc.
Second, read the content

 
   
  
  1. F.read (size)

The parameter size indicates the number of reads, which can be omitted. If the size parameter is omitted, all contents of the file are read.

 
   
  
  1. F.readline ()

Reads the contents of a file line

 
   
  
  1. F.readlines ()

Read all rows into the array inside [line1,line2,... linen]. This approach is often used to improve efficiency by avoiding the loading of all file content into memory.

Third, write the file

 
   
  
  1. F.write (String)

Writes a string to the file, and if the write ends, you must add "\ n" after the string, and then F.close () to close the file
Iv. content positioning in the document

 
   
  
  1. F.read ()

After reading, the file pointer reaches the end of the file, and if you do it again f.read () will find empty content, and if you want to read everything again, you must move the anchor pointer to the beginning of the file:

 
   
  
  1. F.seek (0)

The format of this function is as follows (in bytes):

 
   
  
  1. F.seek (offset, from_what)

From_what represents the start of the read position, offset means moving from from_what to a certain distance, such as F.seek (10, 3) is positioned to the third character and then 10 characters later. A from_what value of 0 indicates the beginning of the file, which can also be omitted, and by default 0 is the beginning of the file. The following gives a

 
   
  
  1. F  =  Open ('/tmp/workfile ', ' r+ ')
  2. F.write (' 0123456789abcdef ')
  3. F.seek (5) # Go to the 6th byte in the file
  4. F.read (1)
  5. ' 5 '
  6. F.seek ( -3, 2) # Go to the 3rd byte before the end
  7. F.read (1)
  8. ' d '

Five. Close file release resources

File operation completed, be sure to remember to close the file F.close (), you can release resources for other programs to use

Python read and write files in the computer language is widely used, if you want to know the application of the program, the following article will give you a detailed introduction of the relevant content, you will be helpful in the process of learning later, we will detail its application.





One, python in the file, folder operations often used in the OS module and Shutil module common methods.
1. Get the current working directory, that 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 really saved: os.path.exists ()
9. Returns the directory name and file name of a path: Os.path.split ()
Example:

The code is as follows: Os.path.split ('/home/swaroop/byte/code/poem.txt ') Result: ('/home/swaroop/byte/code ', ' poem.txt ')
10. Detach extension: Os.path.splitext ()
11. Get Path name: Os.path.dirname ()
12. Get File Name: Os.path.basename ()
13. Run the shell command: Os.system ()
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 ', and for Linux/unix users, 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)
Second, the document operation method Daquan
1.os.mknod ("test.txt") Create an empty file
2.FP = open ("Test.txt", W) opens a file directly and creates a file if the file does not exist
3. About open mode:
Copy CodeThe code is as follows: R: Open the file as read to read the file information.
W: Open the file in writing and write information to the file. If the file exists, empty the file, and then write the new content
A: Open the file in Append mode (that is, an open file, the file pointer is automatically moved to the end of the file), if the file does not exist, create
B: Open the file in binary mode instead of in text mode. This mode is only valid for Windows or DOS, and Unix-like files are operated in binary mode.
r+: Open in read-write mode
w+: Open in read/write mode (see W)
A +: Open in read/write mode (see a)
RB: Open in binary read mode
WB: Opens in binary write mode (see W)
AB: Open in binary append mode (see a)
rb+: Open in binary read/write mode (see r+)
wb+: Open in binary read/write mode (see w+)
ab+: Open in binary read/write mode (see A +)



File Object Methods
F.close (): Close the file, remember to open the file after opening () must remember to close it, otherwise it will occupy the system open file handle number.
F.fileno (): Gets the file descriptor, which is a number
F.flush (): Flush output cache
F.isatty (): Returns True if the file is an interactive terminal, otherwise false.
F.read ([Count]): reads out the file and, if there is count, reads count bytes.
F.readline (): reads a line of information.
F.readlines ():
Reads all the lines, that is, the information that reads the entire file.
F.seek (Offset[,where]): Moves the file pointer to the offset position relative to where. Where 0 indicates the beginning of the file, this is the default, 1 is the current position, and 2 means the end of the file.
F.tell (): Gets the file pointer position.
F.truncate ([size]): Intercepts the file so that the file size is sized.
F.write (String): writes string strings to the file.
F.writelines (list): Writes a string in a list to a file in a row, is a sequential write to the file, no newline.


Fp.read ([size]) #size为读取的长度, in bytes
Fp.readline ([size]) #读一行, if size is defined, it is possible to return only part of a row
Fp.readlines ([size]) #把文件每一行作为一个list的一个成员 and returns the list. In fact, its internal is through the Loop call ReadLine () to achieve. If you provide a size parameter, size is the total length of the read content, which means that it may be read only to a portion of the file.
Fp.write (str) #把str写到文件中, write () does not add a newline character after Str
Fp.writelines (seq) #把seq的内容全部写到文件中 (multi-line write-once). This function simply writes faithfully and does not add anything behind each line.
Fp.close () #关闭文件.  Python will automatically close files after a file is not used, but this feature is not guaranteed and it is best to develop a habit of shutting them down. If a file is closed and then manipulated, it generates VALUEERROR
Fp.flush () #把缓冲区的内容写入硬盘
Fp.fileno () #返回一个长整型的 "file label"
Fp.isatty () #文件是否是一个终端设备文件 (on UNIX systems)
Fp.tell () #返回文件操作标记的当前位置, starting with the origin of the file
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, it is called the next () function to implement the traversal.
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 from scratch for 0, 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 is made.
Fp.truncate ([size]) #把文件裁成规定的大小, the default is the location that is cropped to the current file action tag. If the size of the file is larger, depending on the system may not change the file, it may be 0 files to the corresponding size, it may be some random content to add.
Three, directory operation method Daquan
1. Create a Directory
Os.mkdir ("file")
2. Copy the file:
Shutil.copyfile ("Oldfile", "NewFile") #oldfile和newfile都只能是文件
Shutil.copy ("Oldfile", "NewFile") #oldfile只能是文件夹, NewFile can be a file, or it can be a destination directory
3. Copy the folder:
4.shutil.copytree ("Olddir", "Newdir") #olddir和newdir都只能是目录, and newdir must not exist
5. Renaming files (directories)
Os.rename ("Oldname", "NewName") #文件或目录都是使用这条命令
6. Moving Files (directories)
Shutil.move ("Oldpos", "Newpos")
7. deleting files
Os.remove ("file")
8. Deleting a directory
Os.rmdir ("dir") #只能删除空目录
Shutil.rmtree ("dir") #空目录, contents of the directory can be deleted
9. Converting a directory
Os.chdir ("path") #换路径



Directory Operations:
os.mkdir ("file")   Create a directory
To copy a file:
shutil.copyfile ("Oldfile", "NewFile")Oldfile and NewFile can only be files .
shutil.copy ("Oldfile", "NewFile")Oldfile can only be a folder, NewFile may be a file, or it can be a destination directory
To copy a folder:
shutil.copytree ("Olddir", "Newdir")Olddir and Newdir can only be directories, and newdir must not exist
Renaming files (directories)
os.rename ("Oldname", "NewName")the file or directory is used by this command
Moving files (directories)
shutil.move ("Oldpos", "Newpos")
Deleting Files
os.remove ("file")
Delete directory
os.rmdir ("dir")only empty directories can be deleted
shutil.rmtree ("dir")empty directories, contents of the directory can be deleted
Converting Catalogs
os.chdir ("path")Change Path


Programming Examples:

#-*-Coding:utf-8-*-import osimport shutil# I. Path operation: Judging, acquiring, and deleting # #. Gets the current working directory, which is the directory path of the current Python script: os.getcwd () #print: Currentpath:f:\learnpythoncurrentpath = OS.GETCWD () print " Currentpath: ", currentpath#2. Returns all files and directory names under the specified directory: Os.listdir () #print: Os.listdir (): [' test.txt ', ' testrw.py ', ' test1.txt ', ' cmd.py ', ' rwfile.py ', ' downloadfile.py ', ' date.py ', ' time.py ', ' datetime.py ', ' file.py ']print ' Os.listdir (): ", Os.listdir (' F:\LearnPython ') Path = "f:\mmmmmmmmm\[email protected]_android1.6_3.2.1.apk" #3. Determine if the given path is really saved: os.path.exists () if os.path.exists (path): #删除一个文件: Os.remove () os.remove (path) else:print path, "not exist "#4. Delete multiple directories: Os.removedirs ("C:\python") #它只能删除空目录 if content inside the directory will not be deleted if os.path.exists ("D:/woqu"): Os.removedirs ("D:/woqu") Else:os.mkdir ("D:/woqu") os.removedirs ("D:/woqu") #5. Determines whether the given path is a file: Os.path.isfile () #print: Trueprint os.path.isfile ("D:\hello\json.txt") #6. Determines whether the given path is a directory: Os.path.isdir () #print: Trueprint os.path.isdir ("D:\hello") #7. Determine if it is an absolute path: Os.path.isabs () #print: Trueprint Os.path. Isabs ("D:\hello") # determines if the link print os.path.islink (' http://www.baidu.com ') #8. Returns the directory name and file name of a path: Os.path.split () #eg os.path.split ('/home/swaroop/byte/code/poem.txt ') Result: ('/home/swaroop/byte/ Code ', ' Poem.txt ') #print: (' D:\\hello ', ' json.txt ') print os.path.split ("D:\hello\json.txt") #9. Detach extension: Os.path.splitext () #print:(' D:\\hello\\json ', '. txt ') print os.path.splitext ("D:\hello\json.txt") #10. Get path name: Os.path.dirname () #print: ' D:\\hello ' Print os.path.dirname ("D:\hello\json.txt") #11. Get file name: Os.path.basename () #print: ' Json.txt ' Print os.path.basename ("D:\hello\json.txt") #13. Indicates the platform you are using: Os.name for Windows, it is ' NT ', and for Linux/unix users, it is ' POSIX ' print ' os.name: ', os.name#14. Linex command If Os.name = = ' POSIX ': #读取和设置环境变量: Os.getenv () with os.putenv () Home_path = os.environ[' home ' Home_path = os.ge Tenv (' HOME ') #读取环境变量 elif os.name = = ' NT ': Home_path = ' d: ' print ' Home_path: ', home_path#15. Gives the line terminator used by the current platform: os.linesep Windows uses ' \ r \ n ', Linux uses ' \ n ' and Mac uses ' \ R ' Print (OS.LINESEP) #16. The path should be a little bit less for Windows and Linux, Windows is split with \ \, and Linux is separated by/, #而用os. Sep automatically chooses which delimiter to use according to the system. Print (OS.SEP) #17. Rename: Os.rename (old, new) #先进入目录os. ChDir ("D:\\hello") print os.getcwd () #18. Then rename the Os.rename ("1.txt", "11.txt") #19. Create a multilevel directory: Os.makedirs ("C:\python\test") os.makedirs (' d:\h\e\l\l\o ') #20. Create a single directory: Os.mkdir ("Test") os.mkdir (' d:\f ') #21. Get file attributes: Os.stat (file) #print: Nt.stat_result (st_mode=33206, st_ino=0l, st_dev=0, st_nlink=0, St_uid=0, St_gid=0, St_ size=497l, st_atime=1346688000l, st_mtime=1346748054l, st_ctime=1346748052l) print os.stat (' D:\hello\json.txt ') #22. Modify file permissions and timestamps: Os.chmod (Path,mode) #这里有介绍: http://blog.csdn.net/wirelessqa/article/details/7974477#23. Terminates the current process: Os.exit () #24. Get File Size: os.path.getsize (filename) print os.path.getsize (' d:/hello/json.txt ')


How to write a list to a file in Python:

Instance:

A = [1,2,3,4,5,6,7,8,9]tmp = []for i in Range (0,len (a), 3): Tmp.append (str (a[i]) + "," +str (a[i+1]) + "," +str (a[i+2]) + "\ n") File ("./a.txt", ' W '). Writelines (TMP)

python reads txt file to list

Instance:

If the TXT file content is: AAA,BBB,CCC ddd,eee,fff I want to read save to the list, display the result is [[AAA,BBB,CCC],[DDD,EEE,FFF]]

Txtpath=r "A.txt" Fp=open (Txtpath) arr=[]for lines in Fp.readlines ():    lines=lines.replace ("\ n", ""). Split (",")    arr.append (lines) fp.close ()


Reference documents:

http://blog.csdn.net/wirelessqa/article/details/7974531

Http://www.cnblogs.com/rollenholt/archive/2012/04/23/2466179.html

Http://zhidao.baidu.co/link?url=CipzeDdunK4rP7S0eGIcbamIu9SeYaW_ Cccf093wawdstxajxd1urbjmz7a2s9pqvnomkagwbkjqkeemlnglankpfjyft9rkfpyuqrfo0ks

Http://zhidao.baidu.com/link?url=MnXJPJhtztPs6kgJkMlea_tkHLRYenQcu7O6IUetgpNQFIoM-9gh4-GuOKvprVOeiguPxM_66mZpatvTzS-iwa



Python file read-write and file directory and folder operations

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.