1. Common functions:
- 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
- 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,
- 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:
- 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
- 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!!!
- 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
Fileobject.flush ()
The function is to write the contents of the buffer to the hard disk
- 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
- 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)
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