Simple file manipulation in Python3 and two simple examples to share

  • 2020-06-07 04:42:29
  • OfStack

preface

First of all, what is called relative path and absolute path, we must understand the dog family program this, but it is hard to avoid children's shoes to forget. So I'm going to code this for your quick recall 1.

Relative paths

The relative path is relative to the current working path of the file

An absolute path

The absolute path is composed of the file name and its full path and drive letters. If it is an Windows system, the absolute path of a file may be:

c:\pythonworkspace\firstpy.py

On Unix platform, the file's absolute path might be: / home sherlockblaze Documents/pythonworkspace/firstpy py

The file type

Files can be roughly divided into text files and base 2 files. Under different operating systems, the files that can be edited with a text editor are all called text files, so other files belong to base 2 files. The advantage of base 2 files over text files is that the processing efficiency of base 2 files is a little higher.

The beginning of reading a file

The idea of reading a file is always the same, and the first step is naturally to open a file. In python we use the open function to open a file using the following code.


input = open(filepath,mode)

Our mode mainly consists of the following ways.

模式 作用
r 读取模式
w 写入模式
a 追加模式
rb 读取2进制数据模式打开文件
wb 写入2进制数据模式打开文件

Again, we have two ways to open the file.

Through the absolute path


input = open("/Users/sherlockblaze/Documents/pythonworkspace/Test.txt","r")

Relative path (note that relative path allows me to open files in my current working directory, that is, if my.py file exists under/User/sherlock/Documents, the files I opened under relative path will also exist under current path)


input = open("Test.txt","r")

Pay attention to

When we open a file with an absolute path under Windows, we need to prefix the absolute file name with an r prefix to indicate that the string is a one-line string, which allows the python interpreter to interpret the backslash in the file as a literal backslash. Such as:


input = open(r"d:\pythonworkspace\Test.txt","r")

If we do not add r as a prefix, we need to change the above statement with an escape character to look like this:


input = open("d:\\pythonworkspace\\Test.txt","r")

Writes data to a file

We first open the file by writing, and then write 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 write SherlockBlaze is the most handsome guy to the Test.txt file in the current directory! And it's important to note that after we write the file, we call close() Method closes the file flow.

Common minor characteristics

When a file is opened in w mode, the open function creates a new file if it does not exist, and if it does, the contents of the file are overwritten by the heart. When we open a file in read/write mode, a special tag called a file pointer is added inside the file. Both read and write take place at the current location of the pointer.

Determine if the file exists

In order to avoid misoperation, we can pass os.path The isFile function in the module determines whether a file exists. That is:


import os.path
is os.paht.isfile("Test.txt"):
 print("Test.txt exists")
else:
 print("Test.txt doesn't exists")

Simple applet

Enter the file path and count the number of occurrences of each letter from it


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')] += 1
main()

First, create an array. Every time a character is read, add 1 to the number at the corresponding position. Finally, iterate through the array to get the output.

Download the source code for the site and write it to the destination file


import sys
import urllib
import urllib.request
import os.path
def 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 html
def 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()

Such as I http input url: / / www game2. cn /, in the input file: game2. txt. You can download and enter the corresponding html into the es117EN2.txt file in the current working directory.

conclusion


Related articles: