With the old Ziko Python red-headed (1) _python

Source: Internet
Author: User
Tags one more line in python

These two days the body does not give strength, arrears the daily lecture of the agreement, reader forgive.

Red-headed, is a special color of a country thing, there's no need in Python, Python has to deal with the files in the computer, including text, pictures, audio, video, and so on, and a lot of not seen extensions, in Linux, not all things are saved to the file? Files, in Python, are objects, like strings, numbers, etc. that have been learned.

To view the properties of a file in interactive mode first:

>>> 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 ', ' m Ode ', ' name ', ' newlines ', ' next ', ' read ', ' Readinto ', ' readline ', ' readlines ', ' seek ', ' softspace ', ' Tell ', ' Truncate ', ' W Rite ', ' writelines ', ' xreadlines ']

And then some of the properties of the detailed description, that is, reader learning.

Open File

A file was created under a folder, named 130.txt, and entered in the following:

learn python
http://qiwsir.github.io
qiwsir@gmail.com

This file is for three lines.

The following figure shows where this file is stored:

In the screenshot above, I typed Python in the current position (I've set the environment variable, and if you don't, need to write the full boot Python command path), go into interactive mode. In this interactive mode, this action:

>>> f = open ("130.txt")   #打开已经存在的文件 >>> for line in
F:
...   Print Line
... 
Learn python

http://qiwsir.github.io

qiwsir@gmail.com

To open the file, assign a variable F, which means that the variable F is connected to the object file 130.txt with a line (object reference).

Next, use for to read the contents of the file, just as you would read a previously learned sequence object, such as list, str, tuple, and assign each row in the read file to the variable line. It can also be understood that a for loop reads the contents of a file one line at a while. Each time a row is scanned, the line ending symbol is encountered \ n indicates that the bank ends, then the next line.

As you can see from the printed results, each row is the same as the one seen in the previous file. There is only one more line between lines and lines, when the content of the article is displayed, there is no this blank line. Perhaps this does not matter, but, still need to delve into, can suddenly.

In the original text, there is a line ending symbol \ n, which indicates a newline. In the For statement rollup, the print line means that after each printing of the lines, a newline is added, after the object is printed out. So, at the end of each line, there are two \ n, that is, \ n \ nand a blank line appears in print.

>>> f = open (' 130.txt ') >>> for line in
F:
...   Print line,   #后面加一个逗号, removed the original default increase \ n, see, less empty lines.
... 
Learn python
http://qiwsir.github.io
qiwsir@gmail.com

Did you encounter such a situation in the course of the above operation?

>>> f = open (' 130.txt ') >>> for line in
F:
...   Print line,
... 
Learn python
http://qiwsir.github.io
qiwsir@gmail.com

>>> for line2 in F:   # After reading the contents of the file through the For loop, read again
...   Print Line2   #然后打印, and the results show what is the problem?
... 
>>>

If reader does not encounter the above problems, you can try. Encountered, this is to dispel doubts. It's not a mistake because the file content was read the previous time, and it's at the end of the file. Repeat the operation, starting from the end to continue reading. Of course there's nothing to show, but Python doesn't think it's a mistake, because it says later, maybe before this read, you've added something to the file. So what if you want to read it again? Just take it from the other side.

Specifically remind reader because the current interaction mode is started in the directory where the file is located, so the equivalent of this lab and file 130.txt is the same directory, when we open the file 130.txt, we think it is in this directory open, if the file is not in this directory, you need to write clear path.

For example: In the previous directory (~/documents/itarticles/basicpython), join me into that directory, run interactive mode, and then try to open the 130.txt file.

>>> f = open ("130.txt")
Traceback (most recent call last):
 File "<stdin>", line 1, in <module> ;
IOError: [Errno 2] No such file or directory: ' 130.txt '

>>> f = open ('./codes/130.txt ')   #必须得写上路径了 (note, win The dows path is \ Delimited and needs to be escaped. To the escape character, reader to see the previous lecture) >>> for line in
F:
...   Print Line
... 
Learn python

http://qiwsir.github.io

qiwsir@gmail.com

>>> 

Create a file

In the experiment above, a file that is already in existence is open. How do I create a file?

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

So you create a file? and write the contents of the file? Look again:

It really created the new file, and there was that sentence in it.

Reader noticed no, this time we also use the open () function, but a "w", which is to tell Python in what mode to open the file. That is, opening the file with open () can have different modes to open. Look at the table below:

Mode description R Opens the file as read and reads the file information. W opens the file as write, and can write information to the file. If the file exists, empty the file and write new content A to open the file in Append mode (that is, an open file, the file pointer is automatically moved to the end of the file), and if the file does not exist, create r+ to open the file read-write and write to the file. w+ the contents of the file, and then opens the file in read-write mode. A + reads and writes the file and moves the file pointer to the end of the file. b opens the file in binary mode, rather than in 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 open files in different modes can be read and write related. So, what if the pattern isn't written, like before? That is, the default is R mode, read-only way to open the file.

>>> f = open ("130.txt")
>>> F
<open file ' 130.txt ', mode ' R ' at 0xb7530230>
>> > f = open ("130.txt", "R")
>>> F
<open file ' 130.txt ', mode ' R ' at 0xb750a700>

In this way, you can see what mode the currently open file is in, which shows that the two modes are the same effect. Explain each of the patterns below

"W": Opens the file as a write to write information to the file. If the file exists, empty the file, and then write the new content

131.txt the file is present, built in front, and written in a word: This is a file

>>> fp = open ("131.txt") >>> for line in
fp:     #原来这个文件里面的内容
...   Print Line
... 
This is a file
>>> fp = open ("131.txt", "W")  #这时候再看看这个文件, what else is in it? Is it empty?
>>> fp.write ("My name is Qiwsir.\nmy website is Qiwsir.github.io") #再查看内容
>>> fp.close ()

To view the contents of a file:

$ cat 131.txt #cat是linux下显示文件内容的命令, this is where you want to display 131.txt content, my
name is Qiwsir.
My website is Qiwsir.github.io

"A": Opens the file in Append mode (that is, when a 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")  #向文件中追加
> >> fp.close ()              #这是关闭文件, must form a habit, after writing the content to close

To view the contents of a file:

$ cat 131.txt I
name is Qiwsir.
My website are qiwsir.github.io
aha,i like program

The rest of the project is out of the story. Reader can experiment on his own.

We'll get here first and continue with the document tomorrow. Cold medicine to eat, 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.