Python file Operation two

Source: Internet
Author: User

1. Common functions:

    1. Fileobject.read ([size])
      The size is the length of the read, in bytes. If you do not specify a parameter, read all at once
      Content, returned as a string, with a "\ n" symbol at the end of each line.
      code Example 1:
      with open("text.txt","r") as pf:content = pf.read()print content

Results:
Abcede
123
This is a test file operation JFEDCBA

code Example 2:

with open("text.txt","r") as pf:    content = pf.read(2)    print content

Results:
READ: AB

    1. Fileobject.readline ([size])
      A row, if given a size, it is possible to return only a portion of a line, returning as a string
      And ends with a newline character "\ n". After reading a line, the file action tag moves to the next line of
      Beginning
      List of questions 1
with open("text.txt","r") as pf:    content = pf.readline()    print content

Results:
The way of the university, in the Mingmingde, in the pro-people, in striving.
Title 1:

with open("text.txt","r") as pf:    content = pf.readline(15)    print content

Results:
The way of the university,

    1. Fileobject.readlines ([size])
      Each line of the file as a member of a list, is a string, and ends with a newline character "\ n" and returns the list. The inside of this function is implemented by looping through calls to ReadLine (). If the size parameter is specified to read the length of the specified contents of the file, it is possible to read only part of the file at this time
with open("text.txt","r") as pf:    content = pf.readlines()    print content    for line in content:        print line

Results:

    1. Fileobject.write (str)
      Write str to the file, the default is no line break, so if you want to change the line, you have to manually add a newline character '
with open("test.txt","w") as pf:    pf.write("我是最帮的!!\n学习文件写入操作")

Results:
I am the most help!!
Learning File Write operations

    1. Fileobject.writelines (seq)
      Writes the contents of the SEQ (sequence) to the file (multi-line write-once). Also does not automatically add line breaks
      Such as:
content = "我是最帮的!!\n学习文件写入操作,加油!!!"with open("test.txt","a") as pf:    pf.writelines(content)

Results:
I am the most help!!
Learn file write operations I am the most help!!
Learn the file write operation, refueling!!!

    1. Fileobject.close ()
      The close () method of the file object flushes any information that has not yet been written in the buffer and closes the file, which can no longer be written. When a reference to a file object is re-assigned to another file, Python closes the previous file. Closing a file with the close () method is a good habit. If the file is closed, the operation of the file will generate a valueerror error, but if you do not close the file in a timely manner, it is possible to generate a sentence
      Handle leakage, loss of data
      #打开文件准备写文件
fp = open( "c:\\test.txt",‘w‘)print u"文件名:", fp.name#关闭文件fp.close()print u"文件是否关闭:", fp.closed

Results:
File name: test.txt
Whether the file is closed: True

    1. Fileobject.flush ()
      The function is to write the contents of the buffer to the hard disk

    2. Fileobject.tell ()
      Returns the current position of the file action tag, with the beginning of the file as the Datum point
with open("test.txt","r") as pf:    print u"当前文件操作标记位置为:", pf.tell()    line = pf.readline()    print u"读取一行后文件操作标记位置为:", pf.tell()

Results:
The current file action tag position is: 0
After reading a row, the file operation marks the location: 23

    1. Fileobject.seek (offset[, from])
      The tell () method tells you the current position within the file, in other words, the next read and write occurs after so many bytes at the beginning of the file. Seek (offset [, from]) This is a file locator function that changes the position of the current file. The offset variable represents the number of bytes to move. The from variable specifies the reference position at which to begin moving bytes. If the from is set to 0 (the default), this means that the beginning of the file is used as the reference location for moving bytes. If set to 1, the current position is used as the reference location. If it is set to 2, then the end of the file will be the reference location. Note that if the file is opened in a or a + mode, the file action tag is automatically returned to the end of the file each time the write operation is made. Test file Test.txt with the following content:
with open("test.txt","r") as fp:    str = fp.read(18)    print u"读取的字符串是 : ", str    # 查找当前位置    position = fp.tell()    print u"当前文件位置 : ", position    # 把指针再次重新定位到文件开头    position = fp.seek(0, 0)    str = fp.read(18)    print u"重新读取字符串 : ", str

Results:
Read the string is: I am the most help!
Current file Location: 18
Re-reading the string: I am the most helpful!

Fileobject.truncate ([size])
The file is cut to the specified size, the default is the location of the current file operation tag. If size is larger than the pieces, depending on the system may not change the file, it may be 0 files to the corresponding size, it may be some random content to add.

with open("test.txt","r") as fp:    print "Name of the file: ", fp.name    line = fp.readline()    print "Read Line: %s" % (line)    print fp.tell()    # Try to read file now    remainingLine = fp.readline()    print "Read Line: %s" % (remainingLine)
    • linecache
      The module allows any row to be obtained from any file, and is optimized using caching, often from a single
      Multiple lines of files.
    • Linecache.getlines (filename)
      Get all the content from a file named filename, output as a list format, to one of the elements in a list of files per action,
      and store it as an element in the list in linenum-1
    • Linecache.getline (Filename,lineno)
      Get the line Lineno from the file named filename. This function never throws an exception – when an error occurs, it
      Return "(line break will be included in the found row).
      If the file is not found, the function will be searched in Sys.path.
    • Linecache.clearcache ()
      Clear the cache if you no longer need the previously obtained rows from Getline ()
    • Linecache.checkcache (filename)
      Check the validity of the cache. If the files in the cache have changed on the hard disk, and you need to update the version, use the
      This function, which executes this function, will talk about the removal of obsolete content. If you omit filename, all entries in the cache are checked.
    • Linecache.updatecache (filename)
      Update the cache with file name filename. If the filename file is updated, use this function to update
    • Linecache.getlines (filename)
      Returns the list. If an error occurs, an empty list is returned.

      1. Ways to delete empty rows
    fp = open(r‘test.txt‘)    aList = []    for item in fp:        if item.strip():            aList.append(item)    fp.close()    fp = open(r‘test2.txt‘, ‘w‘)    fp.writelines(aList)
def delblankline(infile, outfile):    """ Delete blanklines of infile """    infp = open(infile, "r")    outfp = open(outfile, "w")    lines = infp.readlines()    for li in lines:    if li==‘\n‘: #不同操作系统下可能会有不同    print u‘空行‘    if li.split():        outfp.write(li)    infp.close()    outfp.close()if __name__ == "__main__":delblankline("c:\\1.txt","c:\\2.txt")

List of questions:
Data file: Data.log
20160215 000148|0|collect Info Job start|success|
20160215000153|0|collect Info Job
End|success|resultcode = 0000
20160216000120|0|collect Info Job start|success|
20160216000121|0|collect Info Job
End|success|resultcode = 0000
20160217000139|0|collect Info Job start|success|
20160217000143|0|collect Info Job
End|success|resultcode = 0000
Data analysis Requirements:
Each line of content needs to be generated in each row
The first month of the day is the name of the document,
The contents of the file are written to |0| after all
Line content (also including |0| )

Algorithm Analysis:
Iterate through each row, with the first 8 letters of each line
Create a new file, the file name is first 8 letters, and then put the 15th character after all the words
Characters to the file
Close File

fp =open("e:\\data.log")for line in fp.readlines():    filename = line[:14]    content = line[14:]    with open("e:\\"+filename+".txt","w") as fp2:        fp2.write(content+"\n")fp.close()

Python file Operation two

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.