如下所示:
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
|
# -*- coding: utf-8 -*- """ Created on Fri Jul 29 15:49:06 2016 @author: user """ import os #从文件中读取某一行 linecache.checkcache可以刷新cache ,linecache可以缓存某一行的信息 import linecache def GetFileNameAndExt(filename): (filepath,tempfilename) = os.path.split(filename); (shotname,extension) = os.path.splitext(tempfilename); return shotname fileList = [] fileOutList = [] for filename in os.listdir(r 'D:\input' ): pa = 'D:\input\%s' % filename fileList.append(pa) name = GetFileNameAndExt(pa) pa = 'D:\output\%s' % name fileOutList.append(pa) for files in range ( 0 , len (fileList)): lineCount = len ( open (fileList[files], 'rU' ).readlines()) print '====this file %s : %d lines' % (fileList[files],lineCount) print '====有效数据行数 %d lines' % ( lineCount - 14 ) global cnt global mainContent global s1 s1 = '' mainContent = '' cnt = 0 for var in range ( 14 ,lineCount + 1 ): theline = linecache.getline(fileList[files], var) s = theline[ 15 : 13 + 104 ] s = s.replace( ' ' , ',' ) # 将字符串里的k全部替换为8 s = s.replace( ' ' , ',' ) # 将字符串里的k全部替换为8 if var % 2 = = 0 : s + = ( ',' ) s1 = s else : string = s1.strip( '\n' ) + s + '\n' mainContent + = string cnt + = 1 print '====out line count =%d' % cnt # print s print '===final data=====' # print mainContent # 打开一个文件 fo = open (fileOutList[files], "wb" ) fo.write( mainContent); # 关闭打开的文件 fo.close() |
以上这篇python 循环读取txt文档 并转换成csv的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/liang890319/article/details/52066854