Python file operations,

Source: Internet
Author: User

Python file operations,

# The Effects of open () and file () are the same.
# O = open('1.txt ', 'R') # Read-only, open the file, cannot write
# Print f. readline () # Read a row at a time
# Print o. readline () # Read a row at a time

# Print f. read () # read all at once

# Print f. readline () # Read a row first
# Print '+', f. read () # read all remaining, in string format

# Print f. readline () # Read a row first
# Print '+', f. readlines () # Read all remaining items in the List format

# F = file('1.txt ', 'r +') # Read and Write data from the first line of the original file to overwrite the original content.
# F = file('1.txt ', 'w') # write. You cannot read and delete the original file before writing it again. If there is no file, create it,
# F = open('1.txt ', 'W +') # read/write: Delete the original file and write it again. If no file exists, create
# F = open('1.txt ', 'A') # Write, append new content to the end of the file, create if the file does not exist
# F = open('1.txt ', 'a +') # read/write, append new content to the end of the file, create if the file does not exist
# F = open('1.txt ',' B ') # open a binary file, which can be used with r, w, a, and +.
# F = open('1.txt ', 'U') # All line breaks are supported. \ R \ n
# Print f. readline ()

# With open ("1.txt", 'r + ') as f: # the subsequent operation can only be performed once.
# For line in f:
# Print line # read each row

F = open('1.txt ', 'R ')
For I in range (3 ):
Print f. readline ()
Print f. readline ()
Print f. readline ()

# F. write ('aaa bbb \ nccc ddd ')
# F. flush ()#
# F. close ()
# Generally, file stream operations include a buffer mechanism. The write method does not directly write data to a file, but first writes data to a specific buffer in the memory.
# The flush method is used to refresh the buffer, which immediately writes data in the buffer to the file and clears the buffer.
# Normally, when the buffer is full, the operating system automatically writes the buffered data to the file.
# As for the close method, the principle is to call the flush method internally to refresh the buffer and then execute the close operation. This ensures data integrity even if the buffer data is not full.
# If the process unexpectedly exits or normally exits without executing the close method of the file, the content in the buffer will be lost.


Files and folders in python(File operation functions)The operation involves the OS module and shutil module.

Obtain the current working directory, that is, the directory path of the current Python script:OS. getcwd ()

Returns the names of all objects and directories in the specified directory:OS. listdir ()

The function is used to delete an object:OS. remove ()

Delete multiple directories:OS. removedirs (r "c: \ python ")

Check whether the given path is a file:OS. path. isfile ()

Check whether the given path is a directory:OS. path. isdir ()

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

Check whether the given path is actually saved:OS. path. exists ()

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 ')

Separation extension:OS. path. splitext ()

Obtain the path name:OS. path. dirname ()

Get File Name:OS. path. basename ()

Run the shell command:OS. system ()

Read and set environment variables:OS. getenv () and OS. putenv ()

The line terminator used by the current platform is provided:OS. linesepIn Windows, '\ r \ n' is used, in Linux,' \ n' is used, and in Mac, '\ R' is used'

Indicates the platform you are using:OS. nameFor Windows, it is 'nt ', and for Linux/Unix users, it is 'posix'

Rename:OS. rename (old, new)

Create a multilevel directory:OS. makedirs (r "c: \ python \ test ")

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

Get file attributes:OS. stat (file)

Modify the File Permission and timestamp:OS. chmod (file)

Terminate the current process:OS. exit ()

Get file size:OS. path. getsize (filename)


File Operations:
OS. mknod ("test.txt ")Create an empty file
Fp = open ("test.txt", w)Open a file directly. If the file does not exist, create the file.

About open mode:

W open in write mode,
A is opened in append mode (starting from EOF and creating a file if necessary)
R + Enabled in read/write mode
W + is enabled in read/write mode (see w)
A + is enabled in read/write mode (see)
Rb is enabled in binary read mode.
Wb is enabled in binary write mode (see w)
AB is enabled in binary append mode (see)
Rb + is enabled in binary read/write mode (see r +)
Wb + is enabled in binary read/write mode (see w +)
AB + is enabled in binary read/write mode (see a +)

 

Fp. read ([size])# Size indicates the read length, in bytes.

Fp. readline ([size])# Read a row. If the size is defined, only one part of the row may be returned.

Fp. readlines ([size])# Use each row of the file as a member of a list and return this list. In fact, it is implemented by calling readline () cyclically. If the size parameter is provided, size indicates 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 linefeed after str.

Fp. writelines (seq)# Write All seq content to the file (multiple rows are written at one time ). This function is only faithfully written without adding anything to the end of each line.

Fp. close ()# Close the file. Python will automatically close the file after a file is not used, but this function is not guaranteed, it is best to develop your own habit of closing. If a file is closed and operated on it, ValueError is generated.

Fp. flush ()# Write the buffer content to the hard disk

Fp. fileno ()# Return a long integer "file tag"

Fp. isatty ()# Whether the file is a terminal device file (in unix)

Fp. tell ()# Return the current position of the file operation mark, starting with the file

Fp. next ()# Return the next row and move the operation mark of the file to the next row. Use a file... When a statement such as in file is called, the next () function is called to implement traversal.

Fp. seek (offset [, whence])# Move the file to the offset position by marking the operation. 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 is not necessary. If the whence parameter is 0, it indicates that the calculation starts from the beginning, and 1 indicates that the calculation is based on the current position. 2 indicates that the origin is the end of the file. Note that if the file is opened in a or a + mode, the Operation mark of the file is automatically returned to the end of the file each time the file is written.

Fp. truncate ([size])# Crop the file to a specified size. The default value is to crop it to the position marked by the current file operation. If the size is larger than the file size, the file may not be changed depending on the system, or 0 may be used to fill the file with the corresponding size, it may also be added with random content.

 

Directory operation:
OS. mkdir ("file ")Create directory
Copy a 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 target directory.
Copy Folder:
Shutil. copytree ("olddir", "newdir ")Both olddir and newdir can only be directories, and newdir must not exist.
Rename a file (directory)
OS. rename ("oldname", "newname ")This command is used for files or directories.
Move a file (directory)
Shutil. move ("oldpos", "newpos ")
Delete an object
OS. remove ("file ")
Delete directory
OS. rmdir ("dir ")Only empty directories can be deleted.
Shutil. rmtree ("dir ")You can delete empty directories and directories with content.
Conversion directory
OS. chdir ("path ")Change path

 

Example

1Add '_ fc' to the names of all images in the folder'

Python code:

#-*-Coding: UTF-8 -*-
Import re
Import OS
Import time
# Str. split (string) split string
# 'Connector '. join (list) combines the list into a string
Def change_name (path ):
Global I
If not OS. path. isdir (path) and not OS. path. isfile (path ):
Return False
If OS. path. isfile (path ):
File_path = OS. path. split (path) # split the Directory and file
Lists = file_path [1]. split ('.') # split the file and file extension
File_ext = lists [-1] # retrieve the suffix (list slicing operation)
Img_ext = ['bmp ', 'jpeg', 'gif', 'psd ', 'png', 'jpg ']
If file_ext in img_ext:
OS. rename (path, file_path [0] + '/' + lists [0] + '_ fc.' + file_ext)
I + = 1 # note that I here is a trap
# Or
# Img_ext = 'bmp | jpeg | gif | psd | png | jpg'
# If file_ext in img_ext:
# Print ('OK ---' + file_ext)
Elif OS. path. isdir (path ):
For x in OS. listdir (path ):
Change_name (OS. path. join (path, x) # OS. path. join () is useful in path processing.


Img_dir = 'd: \ xx \ images'
Img_dir = img_dir.replace ('\\','/')
Start = time. time ()
I = 0
Change_name (img_dir)
C = time. time ()-start
Print ('runtime: % 0.2f '% (c ))
Print ('% s images processed in total '% (I ))

Output result:

Running Duration: 0.11
109 images processed in total

 

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.