List of articles

    • 1. The principle of reading and writing files :
    • 2. Common file open mode
    • 3. Common methods of file objects
    • 4. Operation related to directory

1. The principle of reading and writing files :

The reading and writing of a file is called I/O operation .

How it works :
 Insert picture description here
.py Files are run with an interpreter , call OS Operating system resources , To manipulate files on disk .

Operation process : When operating a file of a file , First open or create a file , Read or write .
read : From the file to the memory
Write : Put the memory file in the file

Finally, close the resource .

Built in functions : open() You can create or open a file

Rule of grammar :
file=open(filename [mode,encoding]

The open mode is read-only by default
The character encoding format in the default text is gbk

#  author : Internet veteran Xin #  Development time :2021/4/5/0005 8:23file=open('a.txt',encoding='utf-8')print(file.readlines())file.close()

readlines This will write the read data to a list .

2. Common file open mode

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 Pattern :

Parameters meaning
r Open the file in read-only mode , The pointer to the file will be placed at the beginning of the file
w Open... In write mode ,
a Open in append mode ( from EOF Start , Create new files if necessary )
b Open the file in binary mode , Not to be used alone , It needs to be shared with other modes , such as rb
r+ Turn on in read-write mode
w+ Turn on in read-write mode ( See w )
a+ Turn on 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+ )

Case study 1:

#  author : Internet veteran Xin #  Development time :2021/4/5/0005 8:23file=open('b.txt','w')file.write("python")file.close()

This will create a new one b.txt, If it's already there , Just replace .

Binary : Store data in bytes , Can't open with Notepad . such as mp3. picture

3. Common methods of file objects

Method meaning[size]) #size For the read length , With byte In units of
fp.readline([size]) # Read a line , If you define size, It's possible to return only part of a line
fp.readlines([size]) # Take each line of the document as a list A member of , And return this list. In fact, it's internally called through a loop readline() To achieve . Provided size Parameters ,size Is the total length of the read content , That is to say, it may be read-only to a part of the file .
fp.write(str) # hold str Write to file ,write() Will not be in str Followed by a line break
fp.writelines(seq) # hold seq The contents of are all written to the file ( Write multiple lines at once ). This function is just faithfully written , Nothing will be added after each line .
fp.close() # Close file .python Will automatically close a file when it is not in use , But there's no guarantee for this function , It's better to form the habit of closing yourself . If a file is closed and operated on, it will generate ValueError
fp.flush() # Write the contents of the buffer to the hard disk
fp.fileno() # Returns a long integer ” Document labels “
fp.isatty() # Is the file a terminal device file (unix In the system )
fp.tell() # Returns the current location of the file operation flag , Start with the beginning of the file # Go back to the next line , And move the file operation flag to the next line . Put one file be used for for … in file In such a statement , It's called next() Function to achieve traversal .[,whence]) # Move the operation mark of the file to offset The location of . This offset It is usually calculated relative to the beginning of the file , It's usually a positive number . But if you provide whence Parameters are not necessarily ,whence It can be for 0 To start from scratch ,1 It means to take the current position as the origin .2 Indicates that the calculation takes the end of the file as the origin . We need to pay attention to , If the document is a or a+ The mode of is on , Every time I write , The file operation flag will automatically return to the end of the file .
fp.truncate([size]) # Cut the document to the specified size , The default is to cut to the location of the current file operation flag . If size Larger than the size of the file , Depending on the system, you may not change the file , It can also be used 0 Fill up the file to the appropriate size , Maybe it's a random addition .

4. Operation related to directory

Directory operation :

  • os.mkdir(“file”) Create directory
  • Copy file :
    shutil.copyfile(“oldfile”,“newfile”) oldfile and newfile It's just documents
    shutil.copy(“oldfile”,“newfile”) oldfile Only folders ,newfile It could be a file , It can also be the target directory
  • Copy folder :
    shutil.copytree(“olddir”,“newdir”) olddir and newdir It's just a catalog , And newdir Must not exist
  • Rename file ( Catalog )
    os.rename(“oldname”,“newname”) This command is used for files or directories
  • Moving files ( Catalog )
  • Delete file
  • Delete directory
    os.rmdir(“dir”) Only empty directories can be deleted
    shutil.rmtree(“dir”) Empty directory 、 Any directory with content can be deleted
  • Convert Directory
    os.chdir(“path”) Change path

Case study :

#  author : Internet veteran Xin #  Development time :2021/4/5/0005 8:23import os#os.system('notepad.exe')  # Open Notepad #os.system('calc.exe')  # Turn on the calculator ## Call the executable directly #os.startfile('D:\\Software\\WeChat\\WeChat.exe')  # Open the WeChat print(os.getcwd())  # View current directory print(os.listdir('../vippython'))  # see vippython Directory contained in os.mkdir('d_file') # Create folder