python--file processing 1

Source: Internet
Author: User

1. Reading filesMethod: All_the_text = open (' Thefile.txt '). Read () But in order to be safe or to give a name to the open file object, so that after completion can be quickly turned off, to prevent useless file objects occupy memory;
Example: file_object = open (' Thefile.txt ', R) Try:     All_the_text = File_object.read ()            #read () will read all the characters in the file to All_the_ The text goes into a huge string, finally:     File_object.close ()

Do not need to add try,finally statements, but add a better, you can ensure that the file object is closed even if a serious error occurred in the read;
If you want to read in 100 characters, you can also directly:
Text=file.read (100),
If you want a row of rows, you can also:
FF = File_object.readlines ()
#读出来是 the list type, with the ' \ n ' sign at the end of each line, and since it is a line, the print will be displayed in a line of lines: A For lines in Ff:print #此时line类型是string, and FF is still an LIS The T type #这样打印出来不会乱, and if the direct print FF prints the entire FF sequence at one time, and the man is ASCII in the sequence, it causes the man to print out and is particularly chaotic; so one line of print ' and the simplest way:
     for lines in file_object: lines = Line.rstrip (' \ n ')     print line is now a string type, but there is a ' \ n ' sign at the end of each row, and you can add a sentence for the body part: line = Line.rstrip (' \ n ') removes the ' \ n ' sign at the end of each line, while Line.restrip () removes the whitespace by default;
2. Writing FilesOne of the most convenient methods:
Open (' Thefile.txt ', ' W '). Write (All_the_text)

  

However, it is best to assign a name to the file object so that it is easy to close the file object
File_object = open (' Thefile.txt ', ' W ') File_object.write (All_the_text) file_object.close ()
The files that are actually opened with ' W ' or ' WB ' are empty files, and even if the file is not empty, it will be emptied when opened in either way, and it is not emptied when it is opened with ' a ' or ' ab ', and cannot be emptied if it is opened in a ' A + ' mode. , and can also read the file;Note: Either read or write, the cursor will go backwards until the file is opened and, of course, you can use the Seek () function to control the cursor 3. Search for and replace text in FilesReplace (Search_text,replace_text), used for string substitution; 4. Read the specified line from the fileEnumerate (): Traversing elements in a sequence and subscripts
>>> for I,j in enumerate ([' A ', ' B ', ' C ']):     ... Print I,j ... 0 A1 B2 C

  

Function module:
def getline (thefilepath,desired_line_number):     If Desired_line_number < 1:          return ' for     Current_line_ Number,line in Enumerate (open (Thefilepath, ' ru ')):          if Current_line_number = = desired_line_number-1:                    return Line     return '
Library file Linecache When multiple reads are made to a file, Linecache is particularly useful for reading and caching all the text in the specified file, releasing the memory that is used as the cache with ClearCache (), and Checkcache () to ensure that the storage in the cache is up-to-date;
Import linecachetheline = Linecache.getline (thefilepath,desired_line_number) #简单一句就可以得到文件指定行的文本了, convenient bar;

  

5. Working with every word in a fileFirst look at a function split () Python split () slices the string by specifying a delimiter, and if the parameter num has a specified value, separates only the NUM substring instances:
#!/usr/bin/pythonstr = "Line1-abcdef \nline2-abc \nline4-abcd";p rint str.split ();p rint str.split (' ', 1); The above example output is as follows: [' Line1-abcdef ', ' line2-abc ', ' line4-abcd ' [' line1-abcdef ', ' \nline2-abc \NLINE4-ABCD ']
To do some processing of each word, the best is a double loop, one for processing lines, one for processing words
For line in open (Thefilepath): For     word in Line.split ():          dosometingwith (Word)

6. Working with ZIP data6.1 Read data from a ZIP file task checks all the subkeys in a ZIP document and prints the name of the subkey, as well as the size;
#!/usr/bin/env python#encoding:utf-8import zipfile# Opens the zip file with ' r ', z = zipfile. ZipFile ("Text.txt.zip", "R") #从zip文件列表中读取子项名并读取出来计算其字节数for filename in z.namelist ():        print ' File: ', filename        byte = z.read (filename)        print ' has ', Len (Byte), ' byte '

python--file processing 1

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.