python文件处理|python小白 求助 读取txt文件并进行数据处理

|

❶ python 对文件进行处理。

python for symbian 里有一个linechace库,可以实现对文件每行的缓存,便于处理每一行的内容;每行最后的32:T>G,34:G>A可以用正则表达式来处理。*:linechace完全可以在任何Python环境使用。

❷ python 文本文件处理

分隔日志文件存为小文件

#coding:utf-8

#file: FileSplit.py

import os,os.path,time

def FileSplit(sourceFile, targetFolder):

sFile = open(sourceFile, 'r')

number = 100000 #每个小文件中保存100000条数据

dataLine = sFile.readline()

tempData = [] #缓存列表

fileNum = 1

if not os.path.isdir(targetFolder): #如果目标目录不存在,则创建

os.mkdir(targetFolder)

while dataLine: #有数据

for row in range(number):

tempData.append(dataLine) #将一行数据添加到列表中

dataLine = sFile.readline()

if not dataLine :

break

tFilename = os.path.join(targetFolder,os.path.split(sourceFile)[1] + str(fileNum) + ".txt")

tFile = open(tFilename, 'a+') #创建小文件

tFile.writelines(tempData) #将列表保存到文件中

tFile.close()

tempData = [] #清空缓存列表

print(tFilename + " 创建于: " + str(time.ctime()))

fileNum += 1 #文件编号

sFile.close()

if __name__ == "__main__" :

FileSplit("access.log","access")

分类汇总小文件:

#coding:utf-8

#file: Map.py

import os,os.path,re

def Map(sourceFile, targetFolder):

sFile = open(sourceFile, 'r')

dataLine = sFile.readline()

tempData = {} #缓存列表

if not os.path.isdir(targetFolder): #如果目标目录不存在,则创建

os.mkdir(targetFolder)

while dataLine: #有数据

p_re = re.compile(r'(GET|POST)s(.*?)sHTTP/1.[01]',re.IGNORECASE) #用正则表达式解析数据

match = p_re.findall(dataLine)

if match:

visitUrl = match[0][1]

if visitUrl in tempData:

tempData[visitUrl] += 1

else:

tempData[visitUrl] = 1

dataLine = sFile.readline() #读入下一行数据

sFile.close()

tList = []

for key,value in sorted(tempData.items(),key = lambda k:k[1],reverse = True):

tList.append(key + " " + str(value) + '
')

tFilename = os.path.join(targetFolder,os.path.split(sourceFile)[1] + "_map.txt")

tFile = open(tFilename, 'a+') #创建小文件

tFile.writelines(tList) #将列表保存到文件中

tFile.close()

if __name__ == "__main__" :

Map("access\access.log1.txt","access")

Map("access\access.log2.txt","access")

Map("access\access.log3.txt","access")

3. 再次将多个文件分类汇总为一个文件。

#coding:utf-8

#file: Rece.py

import os,os.path,re

def Rece(sourceFolder, targetFile):

tempData = {} #缓存列表

p_re = re.compile(r'(.*?)(d{1,}$)',re.IGNORECASE) #用正则表达式解析数据

for root,dirs,files in os.walk(sourceFolder):

for fil in files:

if fil.endswith('_map.txt'): #是rece文件

sFile = open(os.path.abspath(os.path.join(root,fil)), 'r')

dataLine = sFile.readline()

while dataLine: #有数据

subdata = p_re.findall(dataLine) #用空格分割数据

#print(subdata[0][0]," ",subdata[0][1])

if subdata[0][0] in tempData:

tempData[subdata[0][0]] += int(subdata[0][1])

else:

tempData[subdata[0][0]] = int(subdata[0][1])

dataLine = sFile.readline() #读入下一行数据

sFile.close()

tList = []

for key,value in sorted(tempData.items(),key = lambda k:k[1],reverse = True):

tList.append(key + " " + str(value) + '
')

tFilename = os.path.join(sourceFolder,targetFile + "_rece.txt")

tFile = open(tFilename, 'a+') #创建小文件

tFile.writelines(tList) #将列表保存到文件中

tFile.close()

if __name__ == "__main__" :

Rece("access","access")

❸ PYTHON文件处理相关

search第一个参数扩展名,第二个参数根路径

importosdefsearch(s,path=os.path.abspath('.')):forzinos.listdir(path):ifos.path.isdir(path+os.path.sep+z):print('Currnet:',path)path2=os.path.join(path,z)print('future:',path2)search(s,path2)elifos.path.isfile(path+os.path.sep+z):ifos.path.splitext(z)[1].upper()==s:withopen(os.path.join(path,z),'r')asf:withopen('新的.txt','a')asfw:fw.write(f.read())print(os.path.join(path,z))search('.TXT','H:\TEMP')

❹ Python中文件处理

#coding=gbkLB = [ "张三","李四","王五","12345","abcdfg1233"]# 把上面列表中 含"12"子串的元素存入文件 "C:\\1.txt"f = open("C:\\1.txt","wt")for s in LB: if s.find("12")>=0: #选择性写入,就是条件判断吧? f.write( s+"\n")f.close()# 运行本程序后,查看 C:\1.txt# 内容应为# 12345# abcdfg

❺ python小白 求助 读取txt文件,并进行数据处理

若干个内容格式都一样的txt全删了留一个不就行了

❻ python文件操作问题

由于你写的是相对路径,运行时要注意当前工作目录是什么,在CMD中,就是前面提示符的路径。CMD的默认工作目录是当前用户目录,即C:\Users\用户名,此时运行你的python程序,那么open("yesterday.txt")将会试图在这个目录下寻找yesterday.txt文件,找不到则会报错。

❼ python文件操作

我觉得要逐行的话最好这样写:

forlineinfo.readlines():

至于为什么直接fo可以迭代出每行,应该是open函数返回值的内部实现和返回值类型决定的(应该在c代码里,直接转open定义看不见实现细节)。

❽ python 处理几万个文件

我们可以在GNU / Linux操作系统上使用2.2Ghz四核处理器和16GB RAM。当前脚本仅使用一个处理器。利用其他内核和RAM来更快地处理图像的最佳方法是什么?启动多个Python进程来运行脚本会利用其他内核吗?另一个选择是使用Gearman或Beanstalk之类的东西将工作分配给其他机器。我已经看了多处理库但不知道如何利用它。解决方案启动多个Python进程来运行脚本会利用其他内核吗?是的,如果任务受CPU约束,它将会。这可能是最简单的选择。但是,不要为每个文件或每个目录生成单个进程; 考虑使用像这样的工具,parallel(1)并让它产生每个核心两个进程的东西。另一个选择是使用Gearman或Beanstalk之类的东西将工作分配给其他机器。那可能有用。另外,看看ZeroMQ的Python绑定,它使分布式处理变得非常简单。我已经看了多处理库但不知道如何利用它。比如定义一个函数,process它读取单个目录中的图像,连接到数据库并存储元数据。让它返回一个表示成功或失败的布尔值。我们directories是目录处理的列表。然后import multiprocessingpool = multiprocessing.Pool(multiprocessing.cpu_count())success = all(pool.imap_unordered(process, directories))将并行处理所有目录。如果需要,您还可以在文件级执行并行操作; 这需要更多的修修补补。请注意,这将在第一次失败时停止; 使其容错需要更多的工作。

❾ Python 文件处理的几点注意事项

文件处理在编程中是常见的操作,文件的打开,关闭,重命名,删除,追加,复制,随机读写非常容易理解和使用。需要注意的是文件的安全关闭,采用with语句轻松便捷:with open(pathname,”r”) as myfile: do_some_with(myfile)

❿ python的文件处理

import globimport osimport refilelist = glob.glob('*.txt')p = re.compile(r'<1>(.*)\|(.*)</1>')for fn in filelist: try: fin = open(fn, 'r') fout = open('pro_' + os.path.split(fn)[1], 'w') except: print 'File open error!' os.exit(1) for line in fin.readlines(): if '<0>Rd</0>' in line: line = p.sub('<1>\g<2>|\g<1></1>', line) fout.write(line) fin.close() fout.close()输入文件内容:This is the first line<0>Rd</0><1>a|b</1>some test info<0>Rd</0><1>red|blue</1>输出文件内容:This is the first line<0>Rd</0><1>b|a</1>some test info<0>Rd</0><1>blue|red</1> 补充:见上,稍微改改就好了。


赞 (0)