forked from helencoder/SKE
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfileHandle.py
More file actions
87 lines (77 loc) · 2.23 KB
/
fileHandle.py
File metadata and controls
87 lines (77 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#encoding=utf-8
# 文件处理相关函数
import os
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import codecs
# 获取指定文件数据
def get_file_data(filename, path):
try:
# 进行文章的读取
filePath = os.path.join(path, filename)
fileObject = open(filePath, 'r+')
fileData = fileObject.read()
return fileData
except:
pass
return ''
finally:
pass
# fileObject.close()
# 获取文件目录
def get_file_list(path):
filelist = []
files = os.listdir(path)
for f in files:
if (f[0] == '.'):
pass
else:
# filelist.append(os.path.join(path, f))
filelist.append(f)
return filelist
# 获取文件指定行(第一行)(默认为当前路径下)
def get_file_line_details(filename, path):
if not path:
path = get_cur_path()
filePath = os.path.join(path, filename)
file = codecs.open(filePath, 'r', 'utf-8')
text = file.readline()
return text
# 获取文件第三行数据
def get_file_third_line_details(filename, path):
if not path:
path = get_cur_path()
filePath = os.path.join(path, filename)
file = codecs.open(filePath, 'r', 'utf-8')
count = 1
while count < 6:
text = file.readline()
if count == 5:
tag = text
break
count += 1
return tag
# 写文件操作(默认为追加)
def write_file(filename, data, mode = 'a+'):
curDir = get_cur_path()
filePath = os.path.join(curDir, filename)
fileObject = codecs.open(filePath, mode, 'utf-8')
fileObject.write(str(data))
fileObject.write('\n\n')
# fileObject.close()
# 获取当前文件路径
def get_cur_path():
# 获取脚本路径
path = sys.path[0]
# 判断为脚本文件还是py2exe编译后的文件,如果是脚本文件,则返回的是脚本的目录,如果是py2exe编译后的文件,则返回的是编译后的文件路径
if os.path.isdir(path):
return path
elif os.path.isfile(path):
return os.path.dirname(path)
if __name__ == "__main__":
pass
curPath = get_cur_path()
fileName = 'article.txt'
fileData = get_file_data(fileName, curPath)
print fileData