1. Open File
Open () Opens the file and returns the file object, with many parameters, usually with the first two, open (File,mode). File can be the name of the filename or file directory, mode is open, can be read-only, write, append write, readable writable, and so on.
Open a file, you need to know the directory of the file, or the file is in the current working directory.
(1) Name of the file containing the directory (do not modify the current working directory)
>>> F=open ('e:/python/record.txt') # or F=open (R ' E:\python\ Record.txt ')
#或者f =open (' e:\\python\\record.txt ')>>> f.read ()
(2) file name (modify the current working directory)
import os # insert OS module OS.GETCWD () # Query the current working directory os.chdir ( " e:\ Python ") # Change the current working directory OS.GETCWD () # Query the current working directory and find that the modification was successful f=open ( ' record.txt " ) # Open file return assignment to F F.read () # read file
2. File read and locate (based on the file object method)
The file is read based on location.
Read (): No parameters are set when starting the read, then all are read from the current position to the end.
ReadLine (): reads the current pointer position backwards on that line.
Tell (): The position of the current file pointer.
Seek (Offset,from): Move the pointer, move the offset byte backwards from the From, the From value 0 (start) or 1 (current), or 2 (end). Returns the position where the pointer is located.
A pointer to a file read is not automatically returned, and all of the above operations have continuity. Repositioning is required for each read.
#record.txt file content is 411F=open (R'e:\python\record.txt)F.read ()#' 411 'F.tell ()#3F.read ()#"'F.seek (1,0)#1F.read ()#' One 'F.seek (0,0)#0 foreachinchF:Print(each)#411
3. File Write
The write needs to be set to ' W ' (overwrite) or ' a ' (added at the end) when the file is opened. If you open it in another mode, you need to close it and then open it, or it will go wrong.
Object methods have write (str) and writelines (seq)
F.close () # 2 continues f=open ('record.txt','w+' # Read-write mode to open f.write ('1225') # returns 4f.seek (0,0) # After writing the pointer at the end, re-zeroing before reading f.read () #' 1225 '
4.OS Module
This module is used to access system files.
ImportOSOS.GETCWD ()#get current working directoryOs.chdir (' e:\\python\\ ')#change the current working directory to E:\phthonOs.listdir ()#list files and subdirectories in the current directoryOs.mkdir ('Test')#Create a new folder under the current directory testOs.makedirs (R'1\2\3')#Create a multi -level catalogOs.remove ('Record.txt')#Deleting FilesOs.removedirs (R'1\2\3')#Delete a multi-tiered folderOs.rename ('Record.txt','R.txt')#file or folder renameOs.system ('Calc')#Call Calculator
Common operations for Python files