1、常用函数:
结果: abcede 123 this is a test文件操作jfedcba
代码示例2:
with open("text.txt","r") as pf:
content = pf.read(2)
print content
结果: 读取:ab
with open("text.txt","r") as pf:
content = pf.readline()
print content
结果: 大学之道,在明明德,在亲民,在止于至善。 列题 1:
with open("text.txt","r") as pf:
content = pf.readline(15)
print content
结果: 大学之道,
with open("text.txt","r") as pf:
content = pf.readlines()
print content
for line in content:
print line
结果:
with open("test.txt","w") as pf:
pf.write("我是最帮的!!\n学习文件写入操作")
结果: 我是最帮的!! 学习文件写入操作
content = "我是最帮的!!\n学习文件写入操作,加油!!!"
with open("test.txt","a") as pf:
pf.writelines(content)
结果: 我是最帮的!! 学习文件写入操作我是最帮的!! 学习文件写入操作,加油!!!
fp = open( "c:\\test.txt",'w')
print u"文件名:", fp.name
#关闭文件
fp.close()
print u"文件是否关闭:", fp.closed
结果: 文件名: test.txt 文件是否关闭: True
with open("test.txt","r") as pf:
print u"当前文件操作标记位置为:", pf.tell()
line = pf.readline()
print u"读取一行后文件操作标记位置为:", pf.tell()
结果: 当前文件操作标记位置为: 0 读取一行后文件操作标记位置为: 23
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
结果: 读取的字符串是 : 我是最帮的! 当前文件位置 : 18 重新读取字符串 : 我是最帮的!
fileObject.truncate( [size] ) 把文件裁成规定的大小,默认的是裁到当前文件操作标记的位置。如果size比件的大小还要大,依据系统的不同可能是不改变文件,也可能是用0把文件补到相应的大小,也可能是以一些随机的内容加上去。
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
模块允许从任何文件里得到任何的行,并且使用缓存进行优化,常见的情况是从单
个文件读取多行。 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")
列题: 数据文件: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 数据分析需求: 每行内容需要生成以每行 首年月日为名称的文件, 文件内容写入|0|后的所有 行内容(也包括|0| )
算法分析: 遍历每一行,每行取头8个字母 新建文件,文件名为首8个字母,然后把第15字符后的所有字 符拷贝到文件中 关闭文件
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()