1 Problem
In the process of learning Python, to perform file operations, you must first open a file using the open() function, create the corresponding file object, and then use related methods to read/write operations.
2 Methods
- The basic syntax of the open() function: open(name[, mode])
- name is a string that contains the name of the file to be accessed; mode indicates the mode to open the file, including read-only, write, and append, with the default file access mode being read-only (r).Code Listing 1
By default, the read() method returns the entire text, but you can also specify the number of characters to return.To return the first 5 characters: f=open(“demofile.txt”,”r”) print(f.read(5))readline() reads a line: f=open(“demofile.txt”,”r”) print(f.readline()) - Writing to an existing file: To write to an existing file, you must add a parameter in the open() function: “a” – append – will append to the end of the file; “w” – write – will overwrite the existing content.
Code Listing 2
| f=open(“demofile2.txt”,”a”)f.write(“today is a happy day!”)f.close()Open and read the file and append:f=open(“demofile2.txt”,”r”)print(f.read()) |
- remove() method: to delete a file, you must import the OS module and run its os.remove() function; to delete a folder, use the os.rmdir() method.
Code Listing 3
| Check if the file exists:import osif os.path.exists(“demofile.txt”): os.remove(“demofile.txt”)else: print(“File does not exist”) |
3 Conclusion
Regarding the issue of “file operations in Python”, you can simply use methods for opening, writing, and deleting files, and further learning can allow you to use more methods for application.