Python3 file operations related strength sharing

Source: Internet
Author: User
File operations are often used in our daily use of Python, the following this article is mainly about the Python3 simple file operation and two simple small examples of relevant information, the article introduced in very detailed, the need for friends can reference, the following to see together.

Objective

First introduce what is called the relative path and absolute path, our program dog family must understand this, but inevitably will have children's shoes forget. So the code out for everyone to quickly recall.

Relative path

Relative paths are relative to the current working path of the file

Absolute path

The absolute path consists of the file name and its full path, and the drive letter, if it is a Windows system, then the absolute path to a file might be:

c:\pythonworkspace\firstpy.py

On UNIX platforms, the absolute path to the file might be:/home/sherlockblaze/documents/pythonworkspace/firstpy.py

File type

Files can be divided into text files and binary files. Under different operating systems, a file that can be edited with a text editor is called a text file, and the other files belong to a binary file. The advantage of binary files compared with text files is that the processing of binary files is more efficient.

Read the beginning of 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 following code to open a file using the Open function.


input = open (Filepath,mode)

Our mode is mainly by the following methods.

Mode function
R Read mode
W Write mode
A Append mode
Rb Read binary data Mode open file
Wb Write binary Data mode open file

Also we have two ways to open the file.

Through absolute paths


input = open ("/users/sherlockblaze/documents/pythonworkspace/test.txt", "R")

By relative path (note that we can open the file under the current working directory by a relative path, that is, if my. py file exists under/user/sherlock/documents, the file that we open with the relative path also exists under the current path)


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

Attention

When we open a file with an absolute path under Windows, we need to add an R prefix to the absolute file name to indicate that the string is a line string, which allows the Python interpreter to interpret the backslash in the file as a literal backslash. For example:


Input = open (r "D:\pythonworkspace\Test.txt", "R")

If we do not add R as a prefix, we need to modify the above statement with the escape character as follows:


input = open ("D:\\pythonworkspace\\test.txt", "R")

Writing data to a file

We first open the file by writing it, and then write the 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 write to the Test.txt file in the current directory Sherlockblaze is the most handsome guy! This sentence, and note that after we have finished writing the file, the calling close() method closes the file stream.

Common small Features

When opening a file with W mode, if the file does not exist, the open function creates a new file, and if the file exists, the contents of the file are overwritten by the contents of the heart. When we open the file in read/write mode, a special tag called the file pointer is added inside the file, and the read and write operation of the file occurs at the current position of the pointer.

Determine if a file exists

To avoid mis-operation, we can os.path determine whether a file exists by using the Isfile function in the module. That


Import os.pathis os.paht.isfile ("Test.txt"): Print ("Test.txt exists") else:print ("Test.txt doesn ' t exists")

Simple Small Program

Enter the file path and count the occurrences of each letter


def main (): filename = input ("Enter a filename:"). Strip () infile = open (filename, "r") counts = [0] for line in Infil E: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 ()

Simple thinking: First create an array, each time you read to a character, the corresponding position of the number to add one, and finally in the loop to get the output.

Download the Web site source code, and then write to the destination 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 <= 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) targ ET = open (F2, "w") content = Html.decode (encoding= "Utf-8") target.write (content) Target.close () main ()

For example I enter the URL http://www.game2.cn/, in the input destination file: Game2.txt. You can download and import the corresponding HTML into the Game2.txt file of your current working directory.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.