文件内建函数(open( ) (建议使用) 和 file( ))
file_object = open(file_name, access_mode = 'r',buffering = -1)
文件对象访问模式:
r 以读方式打开(打开的文件必须已经存在)
w 以写方式打开(打开的文件若存在则首先清空,然后重新创建)
a 以追加模式打开(为了追加数据,所有写入的数据都将追加到文件的末尾)
Python 将文本文件的内容读入变成可以操作的字符串变量非常容易。文件对象提供了三个“读”方法: .read()、.readline() 和 .readlines()
输入:
read() 直接读取直接到字符串,最多读取给定数目的字节。如size没有给定(默认为-1)或为负,文件将被读取到末尾。
readline() 读取打开文件的一行,然后整行,包括行结束符,作为字符串 返回。
readlines() 与上两种方法不同的是:返回的不是字符串,而是读取整个文件内容,然后把所有的行作为一个字符串列表返回。
注:read()和readlines()从文件中读取行时,python并不会删除行结束符,
在python 程序中经常见到:
f = open('myfile', 'r')
data = [line.strip() for line in f.readlines()]
f.close()
输出:
write() 它把含有文本数据或二进制数据块的字符串写到文件中去。(writeline() 等价于write(),故没有此方法)
writelines() 此方法针对列表的操作,它接受一个字符串列表作为参数,将它们写入文件
注:行结束符不会自动加入,如果需要必须在调用write()或writelines()前给每行加入行结束符
文件迭代:
一行一行访问文件:
for eachline in file
....
在python2.2之前,从文件中读取行最好的办法使用 file.readlines( )来读取所有数据,这样程序员可以尽快释放资源,
在python2.2,引进了迭代器和文件迭代,是文件对象成了它们自己的迭代器。
import os
import shutil
with open(r'C:\Jenkins\job\client_scriptmalware\malicious_vt2\log0.txt') as f:
lines = f.readlines()
for line in lines:
if "Decision: [undetermined]" in line or "Decision: [monitoring]" in line:
ff = line.strip().split("on File: [")[1].split("] Rules:")[0]
if not os.path.exists(ff.replace(r"c:\temp\script_malware_detection_fa\data",r"E:\data\script_malware_detection_fa")):
continue
shutil.copy(ff.replace(r"c:\temp\script_malware_detection_fa\data",r"E:\data\script_malware_detection_fa"),"vt2_un")
import random
import os
peoples = []
file_object = open('C:\\SAteam.txt')
while 1:
line=file_object.readline()
if not line:
break;
if line=='':
continue;
line=line.strip('\n')
peoples.append(line)
pass
file_object.close()
GroupOne = random.sample(peoples,5)
for i in GroupOne:
peoples.remove(i)
GroupTwo=random.sample(peoples,5)
for i in GroupTwo:
peoples.remove(i)
print "Group1:",GroupOne
print "Group2:",GroupTwo
print "Group3:",peoples
>>>
Group1: ['Elodie', 'Kai', 'Jane', 'Michael', 'Chaoying']
Group2: ['Hong', 'Graysen', 'Libo', 'Darwin', 'Weimin']
Group3: ['Nico', 'Brooks', 'David', 'Stanley', 'Wade']