python File in , folder ( File operation function ) Operation needs involved os Modules and shutil modular .
Get the current working directory , That is, the present Python Directory path of script work :os.getcwd()
Returns the names of all files and directories in the specified directory :os.listdir()
Function is used 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()
Check whether the given path really exists :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')
Detach extension :os.path.splitext()
Get pathname :os.path.dirname()
Get file name :os.path.basename()
function shell command :os.system()
Read and set environment variables :os.getenv() And os.putenv()
Gives the line terminator used by the current platform :os.linesep Windows use '\r\n',Linux use '\n' and Mac use '\r'
Indicates the platform you are using :os.name about Windows, It is 'nt', And for Linux/Unix user , It is 'posix'
rename :os.rename(old, new)
Create multi level 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") Create an empty file
fp = open("test.txt",w) Open a file directly , If the file does not exist, create the file
about open pattern :
w Open as write ,
a Open in append mode ( from EOF start , Create a new file if necessary )
r+ Open in read-write mode
w+ Open in read-write mode ( See also 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 also w+ )
ab+ Open in binary read / write mode ( See a+ )
fp.read([size]) #size Is the length of the read , with byte Unit
fp.readline([size]) # Read a line , If defined size, It is possible to return only part of a line
fp.readlines([size])
# Treat each line of the file as a list A member of , And back to this list. In fact, it is called internally through a loop readline() To achieve . If provided size parameter ,size Is the total length of the read content , In other words, it may be read-only to part of the file .
fp.write(str) # hold str Write to file ,write() It's not going to be here str Followed by a newline character
fp.writelines(seq) # hold seq Write all the contents to the file ( Multi line write once ). This function is only faithfully written , You don't add anything after every line .
fp.close() # Close the file .python Will automatically close a file when it is not in use , However, this function is not guaranteed , It's better to get into the habit of closing .
If a file is operated on after it is closed, the ValueError
fp.flush() # Write the contents of the buffer to the hard disk
fp.fileno() # Returns a long integer ” file label “
fp.isatty() # Is the file a terminal device file (unix In the system )
fp.tell()# Returns the current location of the file action tag , Start at the beginning of the file
fp.next() # Go back to the next line , And the file operation mark is moved to the next line . Put one file be used for for … in
file Such a statement , It's called next() Function to achieve traversal .
fp.seek(offset[,whence])
# Move file marking to offset The location of . this offset It is usually calculated relative to the beginning of the file , Generally positive . But if you do whence The parameters are not certain ,whence Can be used for 0 It means starting from scratch ,1 Indicates that the calculation is based on the current position .2 Indicates that the calculation is based on the end of the file . Need attention , If the file is a or a+ Mode on , Every time a write operation is performed , The file action tag is automatically returned to the end of the file .
fp.truncate([size])
# Cut the document to a specified size , The default is to cut to the location of the current file operation mark . If size Larger than the size of the file , Depending on the system, the file may not be changed , Or maybe it's with 0 Fill the file to the appropriate size , It could be a random addition .
Directory operations :
os.mkdir("file") Create directory
Copy file :
shutil.copyfile("oldfile","newfile") oldfile and newfile All can only be files
shutil.copy("oldfile","newfile") oldfile It can only be a folder ,newfile It can be a file , It can also be the target directory
Copy folder :
shutil.copytree("olddir","newdir") olddir and newdir They can only be catalogues , And newdir Must not exist
rename file ( catalog )
os.rename("oldname","newname") Files or directories use this command
move file ( catalog )
shutil.move("oldpos","newpos")
Delete file
os.remove("file")
Delete directory
os.rmdir("dir") Only empty directories can be deleted
shutil.rmtree("dir") Empty directory , Any directory with contents can be deleted
change directory
os.chdir("path") Changing paths
Python Read and write files
1.open
use open Remember to call the file object after opening the file close() method . For example, it can be used try/finally Statement to ensure that the file is finally closed .
notes : Can't put open Statement in try In the block , Because when an exception occurs when opening a file , File object file_object Unable to execute close() method .
2. read file
Read text file
Read binary files
Read everything
Read fixed bytes
Read each line
If the file is a text file , You can also traverse the file object directly to get each line :
3. Writing documents
Write text file
Write binary file
Add write file
Write data
Write multiple lines
be careful , call writelines Writing multiple rows is better than using write Write once higher .
When processing log files , This is often the case : The log file is huge , It is impossible to read the whole file into memory for processing at one time , For example, you need to use a physical memory for 2GB One on the machine
2GB Log file for , We may want to deal with it at a time 200MB Content of .
stay Python in , Built in File Object directly provides a readlines(sizehint) Function to do this . Take the following code as an example :
Every call readlines(sizehint) function , Will return about 200MB
Data for , And the returned data must be complete row data , Most of the time , The number of bytes of data returned will be slightly less than sizehint Specify a larger value ( Except for the last call
readlines(sizehint) Function ). under normal conditions ,Python The user specified sizehint The value of is adjusted to an integer multiple of the internal cache size .
file stay python It's a special type , It is used in python Operation of external files in the program . stay python Everything is an object ,file It's no exception ,file Yes file Methods and properties of . Now let's look at how to create one file object :
file(name[, mode[, buffering]])
file() Function is used to create a file object , It has a name open(), It may be more vivid , They are built-in functions . Take a look at its parameters . Its parameters are passed as strings .name It's the name of the file .
mode It's open mode , The optional values are r w a U, Respectively stands for reading ( default ) write
Add patterns that support various line breaks . use w or a Mode to open the file , If the file does not exist , Then create it automatically . in addition , use w Mode to open an existing file , The contents of the original file will be emptied , Because the mark of the initial file operation is at the beginning of the file , Write at this time , There is no doubt that the original content will be erased . For historical reasons , Line breaks have different patterns in different systems , For example, in
unix It's one of them \n, And in the windows Yes, it is ‘\r\n’, use U Mode open file , Is to support all line feed patterns , That is to say ‘\r’ '\n'
'\r\n' Can be used to express line break , There will be one tuple Used to store line breaks used in this file . however , Although there are many modes of line feed , get to read python Unified use of \n replace . After the pattern character , You can also add +
b t There are two kinds of signs , It can read and write files at the same time and use binary mode , Text mode ( default ) Open file .
buffering If 0 Indicates no buffering ; If 1 Means to proceed “ row buffering “; If it is a greater than 1 The number of indicates the size of the buffer , It should be in bytes .
file Objects have their own properties and methods . Let's have a look first file Properties of .
closed # Is the tag file closed , from close() rewrite
encoding # Document code
mode # Open mode
name # file name
newlines # Line feed patterns used in files , It's a tuple
softspace #boolean type , Generally 0, It is said to be used for print
file How to read and write :
F.read([size]) #size Is the length of the read , with byte Unit
F.readline([size])
# Read a line , If defined size, It is possible to return only part of a line
F.readlines([size])
# Take each line of the file as a list A member of , And back to this list. In fact, it is called internally through a loop readline() To achieve . If provided size parameter ,size Is the total length of the read content , In other words, it may be read-only to part of the file .
F.write(str)
# hold str Write to file ,write() It's not going to be here str Followed by a newline character
F.writelines(seq)
# hold seq Write all the contents of the file . This function is only faithfully written , You don't add anything after each line .
file Other ways to do it :
F.close()
# Close the file .python Will automatically close a file when it is not in use , However, this function is not guaranteed , It's better to get into the habit of closing . If a file is operated on after it is closed, the ValueError
F.flush()
# Write the contents of the buffer to the hard disk
F.fileno()
# Returns a long integer ” file label “
F.isatty()
# Is the file a terminal device file (unix In the system )
F.tell()
# Returns the current location of the file action tag , Start at the beginning of the file
F.next()
# Return to next line , And mark the next line to the file . Put one file be used for for ... in file Such a statement , It's called next() Function to achieve traversal .
F.seek(offset[,whence])
# Move file marking to offset Location of . this offset It is usually calculated relative to the beginning of the file , Generally positive . But if it does whence The parameters are not necessarily ,whence Can be used for 0 It means starting from scratch ,1 Indicates that the current position is used as the origin for calculation .2 Indicates that the end of the file is taken as the origin for calculation . Need attention , If the file is a or a+ Mode on , Every time a write operation is performed , The file action tag automatically returns to the end of the file .
F.truncate([size])
# Cut the document to a specified size , The default is to cut to the location of the current file operation mark . If size Larger than the size of the file , Depending on the system, the file may not be changed , Or maybe it's with 0 Fill the file to the appropriate size , It may also be added with some random content .
Technology
Daily Recommendation