Open\create file
In python, using the open function, you can open an existing file or create a new file. By default, the new file is created in the folder where the current program is located.
Format: open (file name, access mode), for example
f =open('test.txt','w') #Open the file in write mode, create a new file if it does not exist
If you do not specify the mode when creating a new file, the default is to read mode, but if the new file does not exist, an error will be reported.
# Write
'''
f =open('test.txt','w') #Open the file in write mode, create a new file if it does not exist
f.write("hello python") #Write string to file
f.close() #Close the file operation every time
'''
'''
# Read, read method, read the specified character, locate at the head of the file at the beginning, move backward the specified number of characters each time it is executed
f =open("test.txt","r")
str = f.read(5) #Specify five characters to read
print(str)
str = f.read(5) #Read five more characters, use the file pointer, read backwards in turn, not every time from the beginning
print(str)
f.close()'''
# Read, readline()、readlines()method
f =open("test.txt","r")
# str = f.readline() #Starting from the first line, read only one line at a time
# print(str)
#
# str = f.readline() #Read one more line down
# print(str)
strs = f.readlines() #Read all rows. Output as a list, with each row as an element in the list
# Use enumeration to output the line number of each line
for num,str inenumerate(strs):print("First%d line:%s"%(num+1,str))
f.close()
The rename()
in the os library can complete the renaming of files.
Format: rename (the file name to be modified, the new file name)
import os
os.rename("Graduation thesis.txt","Graduation thesis-final version.txt")|
The remove()
in the os module can complete the file deletion operation
Format: remove (the file name to be deleted)
import os
os.remove("Graduation thesis.txt")
import os
os.mkdir("Directory name")
os.rmdir("Directory name")
import os
os.getcwd()
Recommended Posts