Simple file operations in Python3 and sharing of two simple small instances,
Preface
First, we will introduce what is relative path and absolute path. We may all know this, but we will inevitably forget our children's shoes. So code is provided for you to quickly recall.
Relative Path
The relative path is relative to the current working path of the file.
Absolute path
The absolute path consists of the file name, its complete path, and the drive letter. If it is a Windows system, the absolute path of a file may be:
C: \ pythonworkspace \ firstpy. py
On Unix platforms, the absolute path of the file may be/home/sherlockblze/Documents/pythonworkspace/firstpy. py.
File Type
Files can be divided into text files and binary files. Files that can be edited in a text editor are called text files in different operating systems. Other files are binary files. Compared with text files, binary files are more efficient in processing.
Start of File Reading
The idea of reading a file is always the same. The first step is to open a file. In python, we use the following code to open a file using the open function.
input = open(filepath,mode)
Our mode mainly consists of the following methods.
Mode |
Function |
R |
Read mode |
W |
Write mode |
A |
Append Mode |
Rb |
Open a file in binary data reading mode |
Wb |
Open a file in binary data writing mode |
There are two ways to open a file.
Use absolute path
input = open("/Users/sherlockblaze/Documents/pythonworkspace/Test.txt","r")
Through the relative path (note that we can open the file in the current working directory through the relative path, that is, if my. if the py file exists in/User/sherlock/Documents, the files opened through the relative path will also exist in the current path)
input = open("Test.txt","r")
Note:
In Windows, when we open a file through an absolute path, we need to add an r prefix before the absolute file name to indicate that this string is a line string, in this way, the python interpreter can understand the backslash in the file as a backslash In the aspect. For example:
input = open(r"d:\pythonworkspace\Test.txt","r")
If we do not add r as the prefix, we need to use escape characters to change the preceding statement to the following:
input = open("d:\\pythonworkspace\\Test.txt","r")
Write data to a file
We first open the file by writing, and then write data to the file by calling the write method.
def main(): input = open("Test.txt","w") input.write("SherlockBlaze") input.write("\t is the most handsome guy!\n") input.close() main()
In this way, we have written SherlockBlaze is the most handsome guy to the Test.txt file in the current directory! Note that after writing the fileclose()
Method to close the file stream.
Common minor features
When you open a file in w mode, if the file does not exist, the open function will create a new file. If the file exists, the content in the file will be overwritten by the content. When we open a file in read/write mode, a special mark is added to the file, and the read/write operations of the file occur at the current position of the pointer.
Determine whether a file exists
To avoid misoperation, we canos.path
The isFile function in the module to determine whether a file exists. That is:
import os.pathis os.paht.isfile("Test.txt"): print("Test.txt exists")else: print("Test.txt doesn't exists")
Simple applets
Enter the file path and calculate the number of occurrences of each letter.
def main(): filename = input("Enter a filename: ").strip() infile = open(filename,"r") counts = 26 * [0] for line in infile: countLetters(line.lower(),counts) for i in range(len(counts)): if counts[i] != 0: print(chr(ord('a') + i) + "appears " + str(counts[i]) + (" time" if counts[i] == 1 else " times")) infile.close()def countLetters(line,counts): for ch in line: if ch.isalpha(): counts[ord(ch) - ord('a')] += 1main()
A brief description of the concept: first, create an array. Each time a character is read, add one to the number at the corresponding position, and finally traverse to get the output.
Download the website source code and write it to the target file.
import sysimport urllibimport urllib.requestimport os.pathdef download(url,num_retries = 2): print ('Downloading:',url) try: html = urllib.request.urlopen(url).read() except urllib.URLError as e: print ('Download error:',e.reason) html = None if num_retries > 0: if hasattr(e,'code') and 500 <= e.code <600: return download(url,num_retries-1) return htmldef main(): url = input("Enter a url:\n").strip() f2 = input("Enter a target file:\n").strip() if os.path.isfile(f2): print(f2 + " already exists") sys.exit() html = download(url) target = open(f2,"w") content = html.decode(encoding="utf-8") target.write(content) target.close()main()
For example, enter the URL http://www.game2.cn/and enter the destination file: game2.txt. You can download the file and input HTML to the game2.txt file of the current work directory.
Summary
The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.