本文實例講述了python實現按行切分文本文件的方法。分享給大家供大家參考,具體如下:
python腳本利用shell命令來實現文本的操作, 這些命令大大減少了我們的代碼量。
比如按行切分文件并返回切分后得到的文件列表,可以利用內建的split命令進行切分。為了返回得到的文件列表名,可以先將文件切分到自建的子目錄中,然后通過os.listdir獲取所有文件,再將這些文件移到上一級目錄(即函數參數指定的新目錄),刪除自建子目錄,最后返回該文件名列表。
代碼如下,如發現問題歡迎指正:
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
|
# 創建新路徑 def make_dirs(path): if not os.path.isdir(path): os.makedirs(path) # 獲取文件的行數 def get_total_lines(file_path): if not os.path.exists(file_path): return 0 cmd = 'wc -l %s' % file_path return int(os.popen(cmd).read().split()[0]) # 函數split_file_by_row: 按行切分文件 # filepath: 切分的目標文件 # new_filepath: 生成新文件的路徑 # row_cnt: 每個文件最多包含幾行 # suffix_type: 新文件后綴類型,如兩位字母或數字 # return: 切分后的文件列表 def split_file_by_row(filepath, new_filepath, row_cnt, suffix_type= '-d' ): tmp_dir = "/split_file_by_row/" make_dirs(new_filepath) make_dirs(new_filepath+tmp_dir) total_rows = get_total_lines(filepath) file_cnt = int(math.ceil(total_rows*1.0/row_cnt)) command = "split -l%d -a2 %s %s %s" % (row_cnt, suffix_type, filepath, new_filepath+tmp_dir) os.system(command) filelist = os.listdir(new_filepath+tmp_dir) command = "mv %s/* %s" %(new_filepath+tmp_dir, new_filepath) os.system(command) command = "rm -r %s" %(new_filepath+tmp_dir) os.system(command) return [new_filepath+fn for fn in filelist] |
希望本文所述對大家Python程序設計有所幫助。