Python file read and write and file directory and the operation of the folder to implement code _python

Source: Internet
Author: User
Tags chmod flush posix readline string to file file permissions python script in python
For security reasons, it is best to assign a name to the open file object, so that you can close the file quickly after the operation is completed, preventing some useless file objects from occupying memory. For example, to read from a text file:

file_object = open ('thefile.txt')
try:
all_the_text = file_object.read ()
finally:
file_object.close ()
Five steps to read and write files in Python
First, open the file
Python read and write files are widely used in computer languages. If you want to understand its application program, the following articles will give you a detailed introduction of related content, which will help you in the future learning process. Below we will Describe its application in detail.
code show as below:

f = open ("d: \ test.txt", "w")
Explanation:
The first parameter is the file name, including the path; the second parameter is the mode
'r': Read-only (default. If the file does not exist, an error is thrown)
'w': write only (if the file does not exist, the file is automatically created)
'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.
Reading content
f.read (size)
The parameter size indicates the number of reads and can be omitted. If the size parameter is omitted, it means to read the entire contents of the file.
f.readline ()
Read the contents of a file
f.readlines ()
Read all lines into the array [line1, line2, ... lineN]. This method is often used to avoid loading all file contents into memory, which is more efficient.
Write to file

f.write (string)
Write a string to the file. If the writing is completed, you must add "\ n" to the end of the string, and then f.close () closes the file

Fourth, the content positioning in the file
f.read ()
After reading, the file pointer reaches the end of the file. If f.read () is found again, the empty content is read. If you want to read the entire content again, you must move the positioning pointer to the beginning of the file:
f.seek (0)
The format of this function is (bytes):
f.seek (offset, from_what)
from_what represents the position at which to start reading, and offset represents a certain distance from from_what. For example, f.seek (10, 3) indicates positioning to the third character and shifting back by 10 characters. When the from_what value is 0, it indicates the beginning of the file. It can also be omitted. The default is 0, which is the beginning of the file. Given below
f = open ('/ tmp / workfile', 'r +')
f.write ('0123456789abcdef')
f.seek (5) # Go to the 6th byte in the file
f.read (1)
'5'
f.seek (-3, 2) # Go to the 3rd byte before the end
f.read (1)
'd'
Five, close the file to release resources
After the file operation is completed, you must remember to close the file f.close (), which can release resources for other programs to use
Python read and write files are widely used in computer languages. If you want to understand its application program, the following articles will give you a detailed introduction of related content, which will help you in the future learning process. Below we will Describe its application in detail.

First, the commonly used methods of the os module and the shutil module when operating on files and folders in Python.

1. Get the current working directory, which is the directory path where the current Python script works: os.getcwd ()
2.Return the names of all files and directories in the specified directory: os.listdir ()
3.Function is used to delete a file: os.remove ()
4. Delete multiple directories: os.removedirs (r "c: \ python")
5. Check if the given path is a file: os.path.isfile ()
6. Check if the given path is a directory: os.path.isdir ()
7. Determine if it is an absolute path: os.path.isabs ()
8.Check if the given path really exists: os.path.exists ()
9. Returns the directory name and file name of a path: os.path.split ()
example:
code show as below:
os.path.split ('/ home / swaroop / byte / code / poem.txt') Result: ('/ home / swaroop / byte / code', 'poem.txt')

10. Detach extension: os.path.splitext ()
11. Get the path name: os.path.dirname ()
12. Get the file name: os.path.basename ()
13.Run 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 is 'nt' for Windows and 'posix' for Linux / Unix users
17. Rename: os.rename (old, new)
18. Create a multi-level directory: os.makedirs (r "c: \ python \ test")
19. Create a single directory: os.mkdir ("test")
20. Get the file attributes: os.stat (file)
21. Modify file permissions and timestamp: os.chmod (file)
22. Terminate the current process: os.exit ()
23. Get the file size: os.path.getsize (filename)
Encyclopedia of file operation methods
1.os.mknod ("test.txt") creates an empty file
2.fp = open ("test.txt", w) Open a file directly, create the file if it does not exist
3. About open mode:

Copy the code:

r: Open the file in read mode, you can read the file information.
w: Open the file in write mode, you can write information to the file. If the file exists, empty the file and write new content
a: Open the file in append mode (that is, once the file is opened, the file pointer automatically moves to the end of the file), if the file does not exist, it is created
b: Open the file in binary mode instead of text mode. This mode is only valid for Windows or Dos. 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: open 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 Method
f.close (): Close the file. Remember to close the file after opening it with open (), otherwise it will take up the number of open file handles in the system.
f.fileno (): get file descriptor, a number
f.flush (): Flush the output cache
f.isatty (): Returns true if the file is an interactive terminal, otherwise returns false.
f.read ([count]): Read the file. If there is count, read count bytes.
f.readline (): Read a line of information.
f.readlines ():
Read all lines, that is, read the information of the entire file.
f.seek (offset [, where]): Move the file pointer to the offset position relative to where. Where is 0 for the beginning of the file, which is the default value; 1 for the current position; 2 for the end of the file.
f.tell (): Get the file pointer position.
f.truncate ([size]): Truncate the file so that the file size is size.
f.write (string): write string to file.
f.writelines (list): Writes the strings in the list to the file line by line, and writes to the file continuously without line breaks.

fp.read ([size]) #size is the length of the read, in bytes
fp.readline ([size]) #Read a line, if size is defined, it may return only part of a line
fp.readlines ([size]) # Treat each line of the file as a member of a list and return this list. In fact, it is implemented by calling readline () in a loop. If the size parameter is provided, size is the total length of the read content, that is, it may be read only to a part of the file.
fp.write (str) #Write str to a file, write () does not add a newline after str
fp.writelines (seq) #Write all the contents of seq to the file (multiple lines are written at once). This function is also written faithfully, without adding anything after each line.
fp.close () #Close the file. Python will automatically close a file after it is not used, but this feature is not guaranteed, it is best to develop the habit of closing it yourself. If a file is operated after it is closed, a ValueError is raised
fp.flush () #Write the contents of the buffer to the hard disk
fp.fileno () #Returns a long "file tag"
fp.isatty () # Whether the file is a terminal device file (in a Unix system)
fp.tell () #Return the current position of the file operation mark, starting from the beginning of the file
fp.next () #Return to the next line and shift the file operation mark 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.
fp.seek (offset [, whence]) #Move file mark to offset position. 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, it may not be necessary. The whence can be 0 to calculate from the beginning and 1 to calculate from the current position as the origin. 2 indicates that calculation is performed with the end of the file as the origin. Note that if the file is opened in a or a + mode, the file operation mark will automatically return to the end of the file each time a write operation is performed.
fp.truncate ([size]) #Trim the file to the specified size, the default is to crop to the position of the current file operation mark. If the size is larger than the size of the file, depending on the system, the file may not be changed, the file may be supplemented with 0 to the corresponding size, or it may be added with some random content.

Third, directory operation method Daquan

1. Create a directory

os.mkdir ("file")
2. Copy the file:
shutil.copyfile ("oldfile", "newfile") #oldfile and newfile can only be files
shutil.copy ("oldfile", "newfile") #oldfile can only be a folder, newfile can be a file or a destination directory
3. Copy the folder:
4.shutil.copytree ("olddir", "newdir") #olddir and newdir can only be directories, and newdir must not exist
5. Rename the file (directory)
os.rename ("oldname", "newname") #File or directory use this command
6. Move files (directories)
shutil.move ("oldpos", "newpos")
7. Delete files
os.remove ("file")
8. Delete the directory
os.rmdir ("dir") #Can only delete empty directories
shutil.rmtree ("dir") #Empty directories and directories with content can be deleted
9. Convert directory
os.chdir ("path") #Change path


Directory operation:
os.mkdir ("file") creates a directory
Copy file:
shutil.copyfile ("oldfile", "newfile") both oldfile and newfile can only be files
shutil.copy ("oldfile", "newfile") oldfile can only be a folder, newfile can be a file or a destination directory
Copy folder:
shutil.copytree ("olddir", "newdir") olddir
And newdir can only be directories, and newdir must not exist
Rename file (directory)
os.rename ("oldname", "newname") files or directories use this command
Move files (directories)
shutil.move ("oldpos", "newpos")
Delete Files
os.remove ("file")
Delete directory
os.rmdir ("dir") can only delete empty directories
shutil.rmtree ("dir") Empty directories and directories with contents can be deleted
Conversion directory
os.chdir ("path") for the path

Programming example:
 

#-*-coding: utf-8-*-
 
import os
import shutil
 
# I. Path operations: judgment, acquisition and deletion
 
# 1. Get the current working directory, which is the path of the current Python script: os.getcwd ()
#print: currentpath: f: \ LearnPython
currentpath = os.getcwd ()
print "currentpath:", currentpath
# 2. Return all file and directory names in 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 \ debug_taobao_200003@taobao_android1.6_3.2.1.apk"
# 3. Determine if the given path really exists: os.path.exists ()
if os.path.exists (path):
  #Remove a file: os.remove ()
  os.remove (path)
else:
  print path, "not exist"
 
# 4. Remove multiple directories: os.removedirs ("c: \ python")
#It can only delete empty directories. If there is content in the directory, it will not be deleted.
if os.path.exists ("d: / woqu"):
  os.removedirs ("d: / woqu")
else:
  os.mkdir ("d: / woqu")
  os.removedirs ("d: / woqu")
 
# 5. Determine if the given path is a file: os.path.isfile ()
#print: True
print os.path.isfile ("D: \ hello \ json.txt")
# 6. Determine if the given path is a directory: os.path.isdir ()
#print: True
print os.path.isdir ("D: \ hello")
# 7. Determine if it is an absolute path: os.path.isabs ()
#print: True
print os.path.isabs ("D: \ hello")
# Determine if it is a link
print os.path.islink ('http://www.baidu.com')
# 8. Return 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 the path name: os.path.dirname ()
#print: 'D: \\ hello'
print os.path.dirname ("D: \ hello \ json.txt")
# 11. Get the file name: os.path.basename ()
#print: 'json.txt'
print os.path.basename ("D: \ hello \ json.txt")
 
 
# 13. Indicate the platform you are using: os.name is 'nt' for Windows and 'posix' for Linux / Unix users
print "os.name:", os.name
 
# 14. Commands under linex
if os.name == 'posix':
  #Read and set environment variables: os.getenv () and os.putenv ()
  home_path = os.environ ['HOME']
  home_path = os.getenv ('HOME') #Read environment variables
elif os.name == 'nt':
  home_path = 'd:'
  print 'home_path:', home_path
 
# 15. Give 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 between windows and linux is a little bit different. Windows is divided by \\ and linux is separated by /.
#And using os.sep will automatically choose which delimiter to use according to the system.
print (os.sep)
 
# 17. Rename: os.rename (old, new)
#Enter the directory first
os.chdir ("d: \\ hello")
print os.getcwd ()
# 18. Rename
os.rename ("1.txt", "11.txt")
# 19. Create a multi-level 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 timestamp: os.chmod (path, mode)
#Introduction here: http://blog.csdn.net/wirelessqa/article/details/7974477
# 23. Terminate 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:
Example:

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 read txt file into list
Example:
If the contents of the txt file are: aaa, bbb, ccc
ddd, eee, fff

I want to read and save it to the list, and 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 ()
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.