File Read, Write Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| def fileToString(file):
f = codecs.open(file, "r", "utf-8")
text = f.read()
f.close()
return text
def stringToFile(file,data):
f = codecs.open(file, "w", "utf-8")
f.write(data)
f.close()
def fileToBinary(file):
f = open(file, "rb")
data = f.read()
f.close()
return data;
def binaryToFile(file,data):
f = open(file, "wb")
f.write(data)
f.close()
|
File Read Line
f = open("C:/Bin/f.py", 'r')
while True:
line = f.readline()
if not line: break
print(line)
f.close()
with open("C:/Bin/f.py", 'r') as f:
line = f.readline()
while line:
print(line)
line = f.readline()
f = open("C:/Bin/f.py", 'r')
lines = f.readlines()
for line in lines:
print(line)
f.close()
with open("C:/Bin/f.py", 'r') as f:
lines = f.readlines()
for line in lines:
print(line)
File Read Binary Data
def getint(f,n):
v = 0
l = list(f.read(n))
for i in range(n):
v <<= 8
v |= ord(l[i])
return v
def getdata(f,n):
return list(f.read(n))
def pcap_header(f):
magic = getint(f,4)
major = getint(f,2)
minor = getint(f,2)
getdata(f,16)
print( "%08x" % magic )
with open('C:/Bin/ecpri.pcap','rb') as f:
if pcap_header(f):
pass
File Search Operation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| import codecs
import os
def searchFile(dirname, recurse=False, extensions=None):
list = []
filenames = os.listdir(dirname)
for filename in filenames:
full_filename = os.path.join(dirname, filename)
if os.path.isdir(full_filename) and recurse == True:
list += searchFile(full_filename, recurse=recurse, extensions=extensions)
if os.path.isfile(full_filename):
ext = os.path.splitext(filename)[1]
if extensions is None or ext in extensions:
list.append(full_filename)
return list
|
File Operation with os.walk
1
2
3
4
5
6
7
8
9
10
11
12
| import codecs
import os
def walkDir(dirname,extensions):
list = []
for (path, dirs, files) in os.walk(dirname):
print( path, dirs, files )
for filename in files:
ext = os.path.splitext(filename)[-1]
if ext in extensions:
list.append(os.path.join(path, filename))
return list
|
댓글 없음:
댓글 쓰기