Do not use the red header file when learning Python from old QI (1)

Source: Internet
Author: User
The red header file is a special thing in a country. it is not required in python. in python, files in computers are processed, including text, images, audio, and video files, there are still many file extensions that have never been seen before. in python, files are an object, just like strings and numbers that have been learned. In the past two days, I am in arrears with the agreement to give lectures every day. I am sorry to the audience.

The red header file is a special thing in a country. it is not required in python. in python, files in computers are processed, including text, images, audio, and video files, there are still many extensions that have never been seen before. isn't everything saved to files in linux? Files are an object in python, just like strings and numbers that have been learned.

First, you need to check the attributes of the file in interactive mode:

>>> dir(file)['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'closed', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines']

Then, I will describe some attributes in detail, that is, reading the official website.

Open a file

A file named 130.txtis created under a folder and the following content is entered:

learn pythonhttp://qiwsir.github.ioqiwsir@gmail.com

This file is provided for three rows.

The storage location of the file is displayed:

In the above, I entered python in the current position (I have set the environment variable, if you do not have it, you need to write the full startup python command path) and enter the interactive mode. In this interactive mode, perform the following operations:

>>> F = open ("130.txt") # open an existing file >>> for line in f:... print line... learn pythonhttp: // qiwsir.github.ioqiwsir@gmail.com

Change the value of the opened file to F. This also means that f is connected with the object file 130.txt (Object reference ).

Next, use for to read the content in the file, just like reading a sequence object that has been learned before, such as list, str, and tuple, to read each row in the file, assign a value to the line variable. It can also be understood that the for loop reads the file content one row at a time. Each time a row is scanned, the line ending symbol \ n indicates that the row ends, and then the next line.

The printed results show that each row is the same as the content of the preceding file. There is only an empty line between the row and the row. this blank line is not displayed when the content of the previous article is displayed. This may not matter, but you have to go deep into it to make it happen.

In the original text, each line ends with an ending symbol \ n, indicating a line break. In the for statement summary, print line indicates that each time the line object is printed, a new line is generated, that is, a \ n is added after the line object is printed. In this case, there are two \ n at the end of each line, namely \ n, so an empty line appears in the print.

>>> F = open('130.txt ') >>> for line in f :... print line, # add a comma to the end, and remove the \ n added by default. let's see, there is no blank line .... Learn pythonhttp: // qiwsir.github.ioqiwsir@gmail.com.

Have you ever encountered such a situation during the above operations?

>>> F = open('130.txt ') >>> for line in f :... print line ,... learn pythonhttp: // qiwsir.github.ioqiwsir@gmail.com >>> for line2 in f: # After reading the file content through the for loop, read again ,... print line2 # print the result and display everything. what is the problem ?... >>>

If you have not encountered any of the above problems, try. If you encounter this problem, you will be confused. It is not an error because the content of the file has been read and reached the end of the file. Repeat the operation to continue reading from the end. Of course, nothing is displayed, but python does not think this is an error, because it will be mentioned later, maybe it has added content to the file before this read. So what if I want to read it again? Just start from the new guy.

If the file is not in this directory, you need to write the path clearly.

For example, in the upper-level Directory (~ /Documents/ITArticles/basicpython.pdf, add me to the Directory, run the statement format, and then open the 130.txt file.

>>> F = open ("130.txt") Traceback (most recent call last): File"
 
  
", Line 1, in
  
   
IOError: [Errno 2] No such file or directory: '130.txt '>>> f = open (". /codes/130.txt") # The path must be written (note: The windows path is \ separated and must be escaped. For escape characters, see previous lectures) >>> for line in f:... print line... learn pythonhttp: // qiwsir.github.ioqiwsir@gmail.com >>>>
  
 

Create a file

In the above experiment, an existing file is opened. How to create a file?

>>> nf = open("131.txt","w")>>> nf.write("This is a file")

In this way, a file is created? And write the file content? Let's take a look:

In this case, a new file is created and there is a saying in it.

I didn't pay attention to it. this time we also used the open () function, but there was an extra "w", which was telling python what mode to open the file. That is to say, opening a file with open () can be opened in different modes. See the following table:

ModeDescription r: open a file in read mode to read the file information. W. open the file in write mode and write information to the file. If the file exists, the file is cleared, and new content a is written to open the file in append mode (that is, when the file is opened, the file pointer is automatically moved to the end of the file ), if the file does not exist, create r + to open the file in read/write mode. you can read and write the file. W + removes the file content and opens the file in read/write mode. A + open the file in read/write mode and move the file pointer to the end of the file. B. open the file in binary mode instead of text mode. This mode is only valid for Windows or Dos, and Unix-like files are operated in binary mode.

It is not difficult to see from the table that opening files in different modes can perform related read/write operations. So what if no mode is written, like the previous one? In this way, the default mode is r, and the file is opened in read-only mode.

>>> f = open("130.txt")>>> f
 
  >>> f = open("130.txt","r")>>> f
  
 

You can use this method to view the mode of the currently opened file. the above shows that the two modes have the same effect. The following describes the modes one by one.

"W": open the file in write mode and write information to the file. If the file exists, the file is cleared and new content is written.

The 131.txt file exists and is created earlier, and a sentence is written in it: This is a file

>>> Fp = open ("131.txt") >>> for line in fp: # original content in this file... print line... this is a file >>> fp = open ("131.txt"," w ") # at This time, let's look at This file. what else is there in it? Is it empty? >>> Fp. write ("My name is qiwsir. \ nMy website is qiwsir. github. io") # check the content >>> fp. close ()

View the file content:

$ Cat 131.txt uninstall CATIS the command for displaying the file content in linux. here, we want to display the 131.txt content My name is qiwsir. My website is qiwsir. github. io

"A": open the file in append mode (that is, when the file is opened, the file pointer is automatically moved to the end of the file). If the file does not exist, create

>>> Fp = open ("131.txt"," a ") >>> fp. write ("\ nAha, I like program \ n") # append to the File> fp. close () # This is to close the file. you must develop a habit of closing the file after writing the content.

View the file content:

$ cat 131.txtMy name is qiwsir.My website is qiwsir.github.ioAha,I like program

Other projects are not described in detail. You can experiment on your own.

This lecture is here first, and the document will be continued tomorrow. Cold medicine, sleepy.

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.