Python ways to read and write and create files (must see) _python

Source: Internet
Author: User
Tags flush mkdir readline file permissions python script in python

in Python, files, folders (file action function) operations need to involve OS modules and Shutil modules.

Get the current working directory, which is the directory path of the current Python script work: OS.GETCWD ()

Returns all file and directory names under the specified directory:os.listdir ()

function to delete a file:os.remove ()

Delete multiple directories:os.removedirs (r "C:\python")

Verify that the given path is a file:os.path.isfile ()

Verify that the given path is a directory:os.path.isdir ()

Determine whether it is an absolute path:os.path.isabs ()

Verify that the given path is really stored:os.path.exists ()

Returns the directory name and filename of a path:os.path.split () eg os.path.split ('/home/swaroop/byte/code/poem.txt ') results: ('/home/swaroop /byte/code ', ' poem.txt ')

Detach extension:os.path.splitext ()

Get path name:os.path.dirname ()

Get filename:os.path.basename ()

Run shell command: os.system ()

Reading and setting environment variables:os.getenv () and os.putenv ()

Gives the line terminator used by the current platform:os.linesep Windows uses ' \ r \ n ', Linux uses ' \ n ' and Mac uses ' \ R '

Indicates the platform you are using:os.name for Windows, it is ' NT ', and for Linux/unix users, it's ' POSIX '

Renaming:os.rename (old, new)

To create a multilevel directory:os.makedirs (r "C:\python\test")

Create a single directory:os.mkdir ("test")

Get file properties:os.stat (file)

Modify file permissions and timestamp:os.chmod (file)

Terminate the current process:os.exit ()

Get file Size:os.path.getsize (filename)


file actions:
Os.mknod ("Test.txt") creates an empty file
fp = open ("Test.txt", W) opens a file directly and creates a file if it does not exist

About open mode:

W opens in write mode,
A opens in Append mode (starting with EOF, creating a new file if necessary)
R+ Open in read-write mode
w+ opens in read-write mode (see W)
A + is opened in read-write mode (see a)
RB opens in binary read mode
WB opens in binary write mode (see W)
AB opens in binary append mode (see a)
Rb+ opens in binary read and write mode (see r+)
Wb+ opens in binary read and write mode (see w+)
Ab+ opens in binary read and write mode (see A +)

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 to this list. In fact, its internal is through the Loop call ReadLine () to achieve. If the size argument is supplied, the size is the total length of the read content, meaning that it may be read only as part of the file.

fp.write (str) #把str写到文件中, write () does not add a newline character after Str

fp.writelines (seq) #把seq的内容全部写到文件中 (multiple lines of one-time write). This function is also written faithfully and does not add anything behind each line.

fp.close () #关闭文件. Python will automatically close a file after a file is not used, but this feature is not guaranteed, it is best to develop their own habit of shutting down. If a file is turned on after it has been closed it will produce valueerror

Fp.flush () #把缓冲区的内容写入硬盘

Fp.fileno () #返回一个长整型的 "file label"

Fp.isatty () #文件是否是一个终端设备文件 (in UNIX systems)

Fp.tell () #返回文件操作标记的当前位置, at the beginning of the file as the origin

fp.next () #返回下一行, and the file action tag is shifted to the next line. When you use a file for a statement such as. in file, you call the next () function to iterate through it.

Fp.seek (offset[,whence]) #将文件打操作标记移到offset的位置. This offset is generally calculated relative to the beginning of the file, typically a positive number. However, if the whence parameter is provided, the whence can be calculated from scratch for 0, and 1 indicates the current position is the origin calculation. 2 indicates that the origin is computed at the end of the file. Note that if the file is opened in a A or a + mode, the file action tag is automatically returned to the end of the file each time the write operation is performed.

fp.truncate ([size]) #把文件裁成规定的大小, the default is the location where the current file action tag is to be trimmed. If the size is larger than a file, depending on the system, you may not change the file, or you can use 0 to make up the file to the appropriate size, or you can add some random content.

Directory Operations:
os.mkdir ("file") Create a directory
Copy files:
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 it can be a target 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") files or directories are all using this command
Moving Files (directories)
shutil.move ("Oldpos", "Newpos")
deleting files
os.remove ("file")
Delete Directory
os.rmdir ("dir") can only delete empty directories
shutil.rmtree ("dir") empty directory, content directory can be deleted
Convert Directory
os.chdir ("path") change path

Python Read and write files

1.open
always remember to call the close () method of the file object when you open the file with the. For example, you can use the Try/finally statement to ensure that the file is finally closed.

File_object = open (' Thefile.txt ')
Try
All_the_text = File_object.read ()
Finally
File_object.close ()

Note: The Open statement cannot be placed in a try block because the close () method cannot be executed by the file object File_object when an exception is opened.

2. Read the document
read a text file
input = open (' Data ', ' R ')
#第二个参数默认为r
input = open (' Data ')

Read binary files
input = open (' Data ', ' RB ')

Read all content
File_object = open (' Thefile.txt ')
Try
All_the_text = File_object.read ()
Finally
File_object.close ()

Read fixed bytes
File_object = open (' Abinfile ', ' RB ')
Try
While True:
Chunk = file_object.read (100)
If not chunk:
Break
Do_something_with (Chunk)
Finally
File_object.close ()

Read each line
List_of_all_the_lines = File_object.readlines ()

If the file is a text file, you can also traverse the file object to get each line:

For line in File_object:
Process Line

3. Write a document
Write a text file
Output = open (' Data ', ' W ')

Write binary files
Output = open (' Data ', ' WB ')

Append Write file
Output = open (' Data ', ' w+ ')

Write Data
File_object = open (' Thefile.txt ', ' W ')
File_object.write (All_the_text)
File_object.close ()

Write Multiple lines
File_object.writelines (list_of_text_strings)

Note that calling Writelines writes to multiple lines is higher in performance than write-once writes.

While processing the log file, it is often the case that the log file is huge and it is impossible to read the entire file into memory at once, such as the need to process a 2GB log file on a machine with a physical memory of 2GB, and we may want to process only 200MB of content at a time.
In Python, the built-in File object directly provides a readlines (sizehint) function to accomplish such a thing. Take the following code as an example:

File = open (' Test.log ', ' r ') Sizehint = 209715200 # 200Mposition = 0lines = File.readlines (sizehint) while not File.tell ()- Position < 0:position = File.tell () lines = File.readlines (sizehint)

Each time the ReadLines (sizehint) function is invoked, it returns approximately 200MB of data, which is necessarily the complete row data, and in most cases the number of bytes returned is slightly larger than the value specified by Sizehint (except for the last call to ReadLines ( Sizehint) function. In general, Python automatically adjusts the value of the user-specified sizehint to an integer multiple of the internal cache size.

File in Python is a special type that is used to manipulate external files in a Python program. In Python everything is an object, file is no exception, file has the method and properties of file. Let's look at how to create a file object:


File (name[, mode[, Buffering])
The file () function is used to create a file object that has a name of open () and may be more vivid, which is a built-in function. Take a look at its parameters. Its arguments are passed in string form. Name is the filename of the file.
Mode is the open pattern, and the optional value is R w a U, which represents the pattern of read (default) write-add support for various line breaks. When you open a file in W or a mode, it is created automatically if the file does not exist. In addition, in W mode to open an existing file, the contents of the original file will be emptied, because the first file of the operation of the tag is at the beginning of the file, this time to write operations, will no doubt erase the original content. For historical reasons, line breaks have different patterns in different systems, such as a \ n in Unix, and in Windows ' \ r \ n ', opening files in U mode, supporting all line-wrapping modes, and saying ' \ r ' \ n ' \r\ N ' can represent a newline, and a tuple is used to store the line breaks used in this file. However, although there are multiple modes of line wrapping, it is read in Python and replaced with \ n. At the back of the pattern character, you can also add the two identities of + B T, which means that you can read and write to the file and open the file in binary mode, text mode (default).
Buffering if 0 means no buffering, if 1 means "row buffering", or a number greater than 1 to indicate the size of the buffer, it should be in bytes.

The file object has its own properties and methods. Let's take a look at the properties of the file.


Closed #标记文件是否已经关闭, rewritten by close ()
Encoding #文件编码
Mode #打开模式
Name #文件名
Newlines #文件中用到的换行模式, is a tuple
Softspace #boolean型, typically 0, is said to be used for print

File read and Write method:

F.read ([size]) #size为读取的长度, in bytes
F.readline ([size])
#读一行, if size is defined, it is possible to return only a portion of a row
F.readlines ([size])
#把文件每一行作为一个list的一个成员, and return to this list. In fact, its internal is through the Loop call ReadLine () to achieve. If the size argument is supplied, the size is the total length of the read content, meaning that it may be read only as part of the file.
F.write (str)
#把str写到文件中, write () does not add a newline character after Str
F.writelines (seq)
#把seq的内容全部写到文件中. This function is also written faithfully and does not add anything behind each line.

Other methods of file:

F.close ()
#关闭文件. Python will automatically close a file after a file is not used, but this feature is not guaranteed, it is best to develop their own habit of shutting down. If a file is turned on after it has been closed it will produce valueerror
F.flush ()
#把缓冲区的内容写入硬盘
F.fileno ()
#返回一个长整型的 "File Label"
F.isatty ()
#文件是否是一个终端设备文件 (in Unix systems)
F.tell ()
#返回文件操作标记的当前位置, with the beginning of the file as the origin
F.next ()
#返回下一行, and the file action tag is shifted to the next line. When you use a file for a statement such as. in file, you call the next () function to iterate through it.
F.seek (Offset[,whence])
#将文件打操作标记移到offset的位置. This offset is generally calculated relative to the beginning of the file, typically a positive number. However, if the whence parameter is provided, the whence can be calculated from scratch for 0, and 1 indicates the current position is the origin calculation. 2 indicates that the origin is computed at the end of the file. Note that if the file is opened in a A or a + mode, the file action tag is automatically returned to the end of the file each time the write operation is performed.
F.truncate ([size])
#把文件裁成规定的大小, the default is the location where the current file action tag is to be trimmed. If the size is larger than a file, depending on the system, you may not change the file, or you can use 0 to make up the file to the appropriate size, or you can add some random content.

The above Python read and write, create the file method (must see) is small set to share all the content, hope to give you a reference, also hope that we support cloud habitat community.

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.