python,< > Read File open ()

Source: Internet
Author: User

In the actual operation, we often read the file, this time Python provides us with an open () method for us to read the file, through Help (open), we can get open method

F.close () Turn off read

F.read (Size=-1) reads a file size character, but does not assign a value to size or is assigned a negative number, reads all the remaining characters of the file and returns it as a string.

F.readline () opens in write mode, if the file exists, add at the end

F.write (str) writes the string str to a file

F.writelines (seq) wants a file to be written to a string sequence seq,seq should be an iterative object that returns a string

F.seek (Offset,from) A pointer to the current read file in the file,

F.tell () returns the pointer position of the current file read

#files are file paths, mode is file open, and often there should be a encoding encoding format. Open (file, mode='R', Buffering=-1, Encoding=none, Errors=none, Newline=none, Closefd=true, opener=None)#This is file open mode ." "' r ' Open for reading (default) defaults to read-only ' W ' open for writing, truncating the file first opens in a written way, overwriting The source file ' x ' creates a new file and open it for writing, creating an open and write operation for the files, and if the file already exists, it will error ' a ' open for writing    , the appending to the end of the file if it exists open files as written, and writes are appended to the original file after the write operation ' B ' binary mode opens the file in binary mode    ' t ' text mode (default) Opens ' + ' open a disk file for updating (reading and writing) read-write mode, which can be added to other modes ' U ' universal newline mode (deprecated) Universal line break" "

Suppose we have a file that is stored in the e:\\python\\day-2\\ text. txt directory and the TXT content is "

I like loneliness, like in the dead of night alone in a room, so I can open my heart, and my heart dialogue. I got a reflection and made me more forward.
I asked the heart: "Mind, I am not very concerned about the family?"
The mind is not a language, but it shows a few pictures in my mind.
In the picture, I hurried to close the door to cover up the mother of the "careful" care, the picture, I am dissatisfied with the mood of the food, let dad shake his head helplessly.
Look at these two pictures, I feel extremely guilty, I saw their indifference to the family, indifference to affection.
So, I assure the soul, I must care about the family later. The heart smiled.
I asked the heart: "Mind, I am not very friendly to friends?"
Heart nod nodded, said: "There are friends have difficulties, you can warm help, a friend met a sad thing, you can sincerely to comfort." Treat friends like this! "
I laughed heartily.
Once again, I asked my heart, "Do I respect others?"
Heart helplessly shook his head, said: "You have not, once, a classmate accidentally touched off your book and pen, you to him big accusation; there is a stranger asking you the way, but you are too busy to go home and ignore;
Listen to the heart words, I wan guilt, even some shame. I swear, I must lend a helping hand and treat everyone with a respectful attitude.
In the dialogue of the soul, I reflect on myself.
I change every day, I want to thank the heart, is it take me to grow, it is it, let me grow more harmonious and beautiful!

Then we operate on it by using open.

#Open File>>> f = open ('e:\\python\\day-2\\ text. txt','R')#Read File>>>F.read ()'I like loneliness, like in the dead of night alone in a room, so I can open my heart, and my heart dialogue.
I got a reflection and made me more forward. \u3000\u3000\n
I asked the heart: "Mind, I am not very concerned about the family?" \u3000\u3000\n the mind, but it showed a few pictures in my mind.
\ n the picture, I hurried to the door to hide the sound of my mother's "careful" care, the picture, I am dissatisfied with the mood of the food, let dad shake his head helplessly.
\ n Look at these two pictures, I feel very guilty, I see their indifference to the family, indifference to affection. So, I assure the soul, I must care about the family later.
The heart smiled. \u3000\u3000\n
I asked the heart: "Mind, I am very friendly to friends?" \u3000\u3000\n
Heart nod nodded, said: "There are friends have difficulties, you can warm help, a friend met a sad thing, you can sincerely to comfort." You should treat your friends like this! "\u3000\u3000\n
I laughed heartily. \u3000\u3000\n I once again asked the mind: "Do I respect others?" \u3000\u3000\n
Heart helplessly shook his head, said: "You have not, once, a classmate accidentally touched off your book and pen, you will accuse him greatly; there is a stranger asking you the way, but you are too busy to go home and ignore;" \u3000\u3000\n
Listen to the heart words, I wan guilt, even some shame. I swear, I must lend a helping hand and treat everyone with a respectful attitude. \u3000\u3000\n
In the dialogue of the soul, I reflect on myself.
I change every day, I want to thank the heart, is it bring me to grow, is it, let me grow more harmonious and beautiful!\n\n'#read the file again>>>F.read ()#returned an empty"'

When we read the second time with F.read (), because the cursor has reached the end of the article, the second read is empty. So, when we want to read the file again,

# move read pointer position to start position >>> f.seek (0,0)                              0# Read file line >>>  F.readline ()                              ' I like loneliness, like to be alone in the dead of night, so I can open my heart and talk with my heart. I got a reflection and made me more forward. \u3000\u3000\n'# cursor at current position >>> F.tell ()                              119

Traverse all conversation content (each line)

Traditional method, although the traditional method can print every sentence, but the efficiency is not very high. First look at the traditional method of printing:

# Prime Minister. Set the cursor to the initial value >>> f.seek (0,0)                              0# use list to split f>>> list1 =  List (f)# loop out each sentence  for in list1:                 print(each)    

So to solve this problem, Python gives us a direct way to print.

>>> F.seek (0,0)                              0for in  f:         print(each_line)

Next to the example above, when we want to use write () to the previous file writing operation, we will find that can not write, direct error. Because the mode in which we operate this file is R mode, which is read-only mode:

>>> f.write (" I Love you ")                              Traceback (most recent):  "  <pyshell#20>" in <module>    f.write ("  I love you " not writable

If we want to manipulate a file, then what do I do, first we try open (file, ' W ')

#here the use of W is a write-only operation>>> f = open ('E:\\python\\day-2\\text.txt','W')#We write an I love Python>>> F.write ("I love Python")          13#try to read with read ()>>>F.read ()#We can't read the error.Traceback (most recent): File"<pyshell#24>", Line 1,inch<module>f.read () io. Unsupportedoperation: notreadable#If you do not do the next step at this time, the file you see under the E-disk should be 0kb#if the close () operation is performed, it becomes 1kb, because you have to tell Python that you have#The operation is complete, you can store these things from memory to the hard disk. >>>f.close ()

When we use ' X ' to write a file, be sure to note whether the file already exists in the directory, if there is an error:

>>> e = open ('E:\\python\\day-2\\text.txt','x') Traceback (most recent): File"<pyshell#43>", Line 1,inch<module>e= Open ('E:\\python\\day-2\\text.txt','x') Fileexistserror: [ErrnoFile exists:'E:\\python\\day-2\\text.txt'

But if we do not want to make an error, then we can use W, so that regardless of the existence of the file does not exist will not be an error, because if it exists, it will open the file, if it does not exist, it will create the name of the file.

# W Create d = open ('e:\\python\\day-2\\text.txt','w')

When we want to append content to a file, we use ' a ', which is opened by opening the file and append the input string to the current string.

>>> f = open ('e:\\python\\day-2\\ text. txt','a')                              >>> F.write ("Is you sure?")                              14>>>f.close ()>>> f = open ('e:\\python\\day-2\\ text. txt','R')                              >>>F.read ()'I love Python is you sure?'>>> F.close ()

python,< > Read File open ()

Related Article

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.