python read write and create file methods of must see

  • 2020-05-10 18:28:40
  • OfStack

The operation of files, folders (file manipulation functions) in python involves the os module and shutil module.

Get the current working directory, the directory path where the current Python script works: os.getcwd ()

Returns all files and directory names in the specified directory: os.listdir ()

os.remove () function to delete a file: os.remove ()

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

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

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

Determine if the path is absolute: os.path.isabs ()

Verify that the given path actually exists: os.path.exists ()

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

Split extension: os.path.splitext ()

Get path name: os.path.dirname ()

Get file name: os.path.basename ()

Run shell command: os.system ()

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

Give 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 is 'posix'.

Rename: os. rename (old, new)

Create 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 timestamps: os.chmod (file)

Terminate current process: os.exit ()

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


File operation:
os.mknod (" test.txt ") creates an empty file
fp = open(" test.txt ",w) directly opens a file and creates a file if the file does not exist

About open mode:

w opens as a write,
a opens in append mode (start with EOF and create new files if necessary)
r+ opens in read/write mode
w+ opens in read-write mode (see w)
a+ opens in read-write mode (see a)
rb opens in base 2 read mode
wb opens in base 2 write mode (see w)
ab opens in base 2 append mode (see a)
rb+ opens in base 2 read-write mode (see r+)
wb+ opens in base 2 read-write mode (see w+)
ab+ opens in base 2 read-write mode (see a+)

fp. read([size]) #size is the read length in byte

fp. readline([size]]) # reads 1 line, and if size is defined, it is possible to return only part 1 of 1 line

fp.readlines ([size]) # takes each line of the file as a member of an list and returns this list. It's actually done internally by calling readline() in a loop. If the size parameter is provided, size represents the total length of the read, which means that you may read only part 1 of the file.

fp.write(str) # writes str to a file. write() does not add a newline after str

fp.writelines (seq) # writes all of seq to a file (multiple lines written once). This function also just writes faithfully and does not add anything after each line.

fp.close () # close the file. python will automatically close a file when it's not in use, but that's not guaranteed, so it's best to get into the habit of closing it yourself. ValueError is generated if a file is operated on after closing

flush() # writes the contents of the buffer to the hard disk

fp. fileno() # returns a long integer "file label"

Is fp.isatty () # a terminal device file (unix system)

fp.tell () # returns the current location of the file action tag, starting at the beginning of the file

fp.next () # returns the next line and shifts the file action tag to the next line. Use 1 file for for... Statements like in file are traversed by calling the next() function.

fp.seek (offset[,whence]) # moves the file to the location of offset. This offset1 is generally calculated relative to the beginning of the file, and 1 is generally positive. However, if the parameter whence is provided, it will not be fixed. whence can be 0 to calculate from scratch, and 1 to calculate from the current position as the origin. 2 represents the calculation with the end of the file as the origin. Note that if the file is opened in a or a+ mode, the file action flag is automatically returned to the end of the file each time a write is made.

fp.truncate ([size]) # sizes the file to the specified size, by default, to the location of the current file action flag. If size is larger than the size of the file, depending on the system, it may not change the file, it may fill the file with a 0, or it may be a random addition.

Directory operation:
os.mkdir ("file") creates a directory
Copy file:
shutil.copyfile("oldfile","newfile") oldfile and newfile can only be files
shutil.copy ("oldfile","newfile") oldfile can only be folders, newfile can be either files or target directories
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 the file
os.remove("file")
Delete the directory
os.rmdir ("dir") can only delete empty directories
shutil.rmtree ("dir") empty directory, the contents of the directory can be deleted
Conversion directory
path os. chdir (" ") in path

Python reads and writes files

1.open
Remember to call the close() method of the file object after opening the file with open. For example, you can use the try/finally statement to ensure that the file is closed at the end.

file_object = open('thefile.txt')
try:
all_the_text = file_object.read( )
finally:
file_object.close( )

Note: you cannot put the open statement in the try block, because the file object file_object cannot execute the close() method when an exception occurs when you open the file.

2. Read the file
Read text file
input = open('data', 'r')
The second parameter defaults to r
input = open('data')

Read the base 2 file
input = open('data', 'rb')

Read everything
file_object = open('thefile.txt')
try:
all_the_text = file_object.read( )
finally:
file_object.close( )

Read fixed byte
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 directly traverse the file object to get each line:

for line in file_object:
process line

3. Write files
Write a text file
output = open('data', 'w')

Write a base 2 file
output = open('data', 'wb')

Append file
output = open('data', 'w+')

Write the data
file_object = open('thefile.txt', 'w')
file_object.write(all_the_text)
file_object.close( )

Write more lines
file_object.writelines(list_of_text_strings)

Note that calling writelines to write multiple lines would be better in performance than using write1 for a secondary write.

When dealing with log files, we often encounter situations where the log files are so large that it is impossible to read the entire file into memory for processing at once. For example, if we need to process a log file of 2GB on a machine with 2GB physical memory, we may want to process only the contents of 200MB at a time.
In Python, the built-in File object directly provides an readlines(sizehint) function to do this. The following code is 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 call to the readlines(sizehint) function returns about 200MB of data, and it must always return a full row of data. In most cases, the number of bytes returned is slightly larger than the value specified by sizehint (except for the last call to the readlines(sizehint) function). Typically, Python automatically adjusts the user-specified value of sizehint to an integer multiple of the size of the internal cache.

file in python is a special type used to manipulate external files in python programs. In python, all the first cuts are objects, and file is no exception. file has file methods and properties. Here's how to create an file object:


file(name[, mode[, buffering]])
The file() function is used to create an file object. It has a 1, nicknamed open(), which is probably more like 1. They are built-in functions. Let's look at the parameters. The arguments are passed as strings. name is the name of the file.
mode is the open mode, with an optional value of r w a U, which stands for read (default) write add mode that supports various newline characters. If the file is opened in w or a mode, it is automatically created if it does not exist. In addition, when opening an existing file in w mode, the contents of the original file will be emptied, because the mark of the operation of the file starting from 1 is at the beginning of the file. At this time, the operation of writing will undoubtedly erase the original content. For historical reasons, newline characters have different modes in different systems, such as 1 \n in unix and '\ r\n' in windows. To open a file in U mode is to support all newline modes, which means that '\ r' \n' \r\n' will be used to store the newline characters used in this file. However, although there are many patterns for line feeds, when I read python I used \n instead. After the pattern character, you can add + b t, which means you can read and write to the file at the same time and open the file in base 2 mode and text mode (the default), respectively.
If buffering is 0, it means no buffering. If 1 means "row buffering"; If a number greater than 1 represents the size of the buffer, it should be in bytes.

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


closed # marks whether the file has been closed and is overwritten by close()
encoding # file encoding
mode # opens mode
name # file name
The newline mode used in the newlines # file is 1 tuple
softspace #boolean, type 1 0, said to be used for print

Read and write methods for file:

F.read ([size]) #size is the length read, in byte
F.readline([size])
# reads line 1, and if size is defined, it is possible to return only part 1 of line 1
F.readlines([size])
Take each line of the file as a member of an list and return this list. It's actually done internally by looping through readline(). If you provide the size parameter, size is the total length of the read, which means that you may only read part 1 of the file.
F.write(str)
# writes str to a file. write() does not add a newline after str
F.writelines(seq)
Write all of seq to the file. This function also just writes faithfully and does not add anything after each line.

Other methods of file:

F.close()
Close the file. python will automatically close a file after it is no longer in use, but this is not guaranteed, so it is best to make a habit of closing it yourself. ValueError is generated if a file is operated on after it is closed
F.flush()
Writes the contents of the buffer to the hard disk
F.fileno()
Return 1 long integer "file label"
F.isatty()
Is the # file a terminal device file (in the unix system)
F.tell()
# returns the current location of the file action tag, starting at the beginning of the file at the origin
F.next()
# returns the next line and shifts the file action tag to the next line. Use 1 file for for... Statements like in file are traversed by calling the next() function.
F.seek(offset[,whence])
Move the file marking action to offset. This offset1 is generally calculated relative to the beginning of the file, and 1 is generally positive. However, if the parameter whence is provided, it will not be fixed. whence can be 0 to calculate from scratch, and 1 to calculate from the current position as the origin. 2 represents the calculation with the end of the file as the origin. Note that if the file is opened in a or a+ mode, the file action flag is automatically returned to the end of the file each time a write is made.
F.truncate([size])
Size the file to the specified size, by default, to the location of the current file action flag. If size is larger than the size of the file, depending on the system, it may not change the file, it may fill the file to the corresponding size with 0, or it may add some random content with 1.


Related articles: