Python Notes Lesson II (i): Python file processing

Source: Internet
Author: User

Description

mainly the use of the file () and open () functions, but when checking the help of the open () function, the following instructions are available:

>>> Help (Open) ... Open a file using the file () type, returns a file object.

As a result, two functions are all the same, with only file ().

When enumerating the role of file (), using Help is a good approach, and here's what you should focus on:

Close (...)  |      close ()  -> None or  (perhaps)  an  Integer.  close the file.flush (...)  |      flush ()  -> None.  Flush the  Internal i/o buffer.readline (...)  |      readline ([size])  -> next line from the  file, as a string. readlines (...)  |      readlines ([size])  -> list of strings,  Each a line from the file.seek (...)  |      seek (Offset[, whence])  -> none.  move  to new file position.tell (...)  |      tell ()  -> current file position, an  integer  (May be a long integer). Write (...)   |      write (str)  -> NONE.  WRITE STRING STR  to file.writelines (...)  |      writelines (sequence_of_strings)  -> None.   Write the strings to the file.xreadlines (...)  |      xreadlines ()  -> returns self.



1. Create a file


--Basic format:

f = File (' Test.txt ', ' w ') F = Write (' Hello world! ') F.close ()

• W: Write mode, the file does not exist on the creation, there is automatically overwrite the original content, can only write, can not read;

w+: Read-write mode, but the original file content will be emptied at the beginning, but can be read after the file is written;

• Write the content in memory, if you want to write to disk, you can F.close () close the file or F.flush () write to disk in real time;

• Can not change the mode in real time, only after the file is closed, once again open the definition mode;


--Example:

>>> f = file (' Test.txt ', ' W ') >>> f.write (' Hello world! ') >>> F.flush () [Email protected]:~/seminar6/day2$ more Test.txthello world!


--write () and Writelines ()

• The former can only write to a string, while the latter may write to the list:

>>> F.write ([' A ', ' B ', ' C ']) Traceback (most recent): File "<stdin>", line 1, in <module>ty peerror:expected a character buffer object>>> f.writelines ([' A ', ' B ', ' C ']) >>>



2. Reading files and traversing file contents


--Basic format:

f = File (' test.txt ', ' r ') ===> can not add ' r ', default is the mode F = Read () f.close ()

• R: Default;

r+: Read and write mode, you can try to use, each read a line, the pointer jumps to the next line, when writing, directly overwrite the pointer refers to this line;

RB: in the Windows platform editing files, in Linux in the read with Python, mode to choose "RB", otherwise there may be garbled phenomenon, that is, cross-platform files should pay attention to this point;


--read (), ReadLine, ReadLines () and Xreadlines ()

• The first three are all written directly to the memory, and then read all or a line of the read;

• All are read in an iterative way, that is, the pointer starts at the first line, and when the first row is read, the pointer points to the next line;


-read ()

• Read all the contents of the file:

>>> f = file (' test.txt ', ' R ') >>> F.read () "Hello World!\ni ' m xpleaf.\nnice to meet you!\n" >>> F . Read () ' ===> content has been read, i.e. the pointer is already on the last line, and there is no content behind it

• You can use tell () to view the position of the current pointer:

>>> F.tell () ===>43, which is the last character

• Re-read the contents of the file, you can open it again after f.close (), or you can use F.seek (0):

>>> f.seek (0) ===> re-addressing, let the pointer point to the beginning of the file >>> F.tell () 0>>> print f.read () Hello world! I ' m xpleaf. Nice to meet you!


-readline ()

• Read the contents of the file one line at a string:

>>> f.seek (0) >>> f.readline () ' Hello world!\n ' >>> f.readline () "I ' m xpleaf.\n" >>> F.readline () ' Nice to meet you!\n ' >>> f.readline () '


-readlines ()

• Read the contents of the file in a row, one line at a list, as an element in the list:

>>> f.seek (0) >>> f.readlines () [' Hello world!\n ', ' I ' m xpleaf.\n, ' Nice to meet you!\n ']>>> f . ReadLines () []

• Therefore, habitual usage is: Modify the contents of the file

>>> f.seek (0) >>> filelist = F.readlines () >>> print filelist[' Hello world!\n ', ' I ' m xpleaf.\n ", ' Nice to meet you!\n ']>>> filelist[2] = ' See you next time! ' >>> print filelist[' Hello world!\n ', "I ' m xpleaf.\n", ' See you next time! '

• Open the file in W mode and write it in F.writelines (filelist), which can be used to modify the contents of the file;


-xreadlines ()

• Instead of writing all the contents of the file to memory, write one line at a time, and then recycle the contents of the previous memory by writing the next line;

• It is appropriate to use this method when reading large files.


--Traversal of file contents: Using ReadLines ()

>>> f = file (' test.txt ', ' R ') >>> filelist = F.readlines () >>> for eachline in filelist: ... pri NT Eachline,... Hello world! I ' m xpleaf. Nice to meet you!



3. append file contents


--Basic format:

f = File (' Test.txt ', ' w ') F = Write (' Hello world! ') F.close ()

• The contents of the file are appended to the last line, and if the last line has ' \ n ', append to the next line;


--Example:

>>> f = file (' Test.txt ', ' a ') >>> f.write (' See you next time! ') >>> f.write (' I'll Miss You much!\n ') >>> f.flush () [Email protected]:~/seminar6/day2$ cat Test.txthello world! I ' m xpleaf. Nice to meet you! See you next time! I'll miss you much!



4. File Content Replacement


--Basic format:

Import Fileinputfor Line in Fileinput.input (' filepath ', inplace = 1): line = Line.replace (' OldText ', ' NewText ') print Li Ne

inplace = 1, means to modify the contents of the file, the default value is 0, indicating that the contents of the file is not modified, and "Print line," Only print the contents of the modified in memory (see example below);

inplace = 1 o'clock, if you do not add "print line," The original file content will be empty;

• Additional backup parameters can be added to indicate that backups are made when modifying file contents;


--Example:


-Correct operation:

>>> Import fileinput>>> in Fileinput.input (' test.txt ', inplace = 1, backup = '. Ori '): ... line = Line.replace (' Hello world! ', ' Hello, everyone! ') .. Print line,... [Email protected]:~/seminar6/day2$ ls-l test*-rw-rw-r--1 xpleaf xpleaf 87 September 4 15:32 test.txt-rw-rw-r--1 xpleaf Xplea F 83 September 4 15:19 test.txt.ori[email protected]:~/seminar6/day2$ cat Test.txthello, everyone! I ' m xpleaf. Nice to meet you! See you next time! I'll miss you much!


-if not added inplace = 1 o'clock:

>>> for line in Fileinput.input (' Test.txt '): ... line = line.replace ("nice", ' well ') ... print line,... Hello, everyone!. I ' m xpleaf. Well to meet you! See you next time! I'll miss you much! [Email protected]:~/seminar6/day2$ cat Test.txthello, everyone! I ' m xpleaf. Nice to meet you! See you next time! I'll miss you much!


-If you do not add "print line," When:

>>> for line in Fileinput.input (' Test.txt '): ... line = line.replace ("nice", ' well ') ... >>> for line in Fileinput.input (' test.txt ', inplace = 1): ... line = line.replace (' Hello ', ' Hey ') ... [Email protected]:~/seminar6/day2$ cat test.txt[email protected]:~/seminar6/day2$ ===> file contents have been emptied


This article is from the "fragrant fluttering leaves" blog, please make sure to keep this source http://xpleaf.blog.51cto.com/9315560/1691329

Python Notes Lesson II (i): Python file processing

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.