python文本处理实例_超基础的用Python处理文本实例

'gpu_sim_insn',

'gpu_ipc',

'L1I_total_cache_accesses',

'L1D_total_cache_accesses',

'gpgpu_n_tot_thrd_icount',

'gpgpu_n_tot_w_icount',

'gpgpu_n_mem_read_local',

'gpgpu_n_mem_write_local',

'gpgpu_n_mem_read_global',

'gpgpu_n_mem_write_global',

'gpgpu_n_mem_texture',

'gpgpu_n_mem_const',

'gpgpu_n_load_insn',

'gpgpu_n_store_insn',

'gpgpu_n_shmem_insn',

'gpgpu_n_tex_insn',

'gpgpu_n_const_mem_insn',

'gpgpu_n_param_mem_insn'

代码如下:

import re

import sys

import os,glob

#定义目录:目录下有多个文件需要处理

path = 'D:\\GPUClusters\\Stargazer-master\\EXP_RESULT'

#定义输出文件

fout = open("res.txt",'w')

x = [

'gpu_sim_insn',

'gpu_ipc',

'L1I_total_cache_accesses',

'L1D_total_cache_accesses',

'gpgpu_n_tot_thrd_icount',

'gpgpu_n_tot_w_icount',

'gpgpu_n_mem_read_local',

'gpgpu_n_mem_write_local',

'gpgpu_n_mem_read_global',

'gpgpu_n_mem_write_global',

'gpgpu_n_mem_texture',

'gpgpu_n_mem_const',

'gpgpu_n_load_insn',

'gpgpu_n_store_insn',

'gpgpu_n_shmem_insn',

'gpgpu_n_tex_insn',

'gpgpu_n_const_mem_insn',

'gpgpu_n_param_mem_insn'

]

#改变路径

os.chdir(path)

#遍历目录下的所有文件

for filename in os.listdir():

fs = open(filename,'r+')

#处理文件中的每一行数据

for line in fs.readlines():

a = line.split()

if a != [] and a[0] in x:

fout.write(a[-1]+'\t')

if a[0] == 'gpgpu_n_param_mem_insn':

fout.write('\n')

break

fout.write('\n')

fout.close()

解释一下代码中的几个问题:

1.在一个目录下有多个文件,每个文件都要读取一次,并进行文本处理,如何实现?

#比如d:\work下面是你要读取的文件,代码可以这样写:

import os

path = 'd:\\work' #or path = r'd:\work'

os.chdir(path)

for filename in os.listdir():

file = open(filename,'r')

for eachline in file.readlines():

#process eachline

2.Python中.read(), .readline(), .readlines()区别?

Python 将文本文件的内容读入可以操作的字符串变量非常容易。文件对象提供了三个“读”方法: .read()、.readline() 和 .readlines()。每种方法可以接受一个变量以限制每次读取的数据量,但它们通常不使用变量。 .read() 每次读取整个文件,它通常用于将文件内容放到一个字符串变量中。然而 .read() 生成文件内容最直接的字符串表示,但对于连续的面向行的处理,它却是不必要的,并且如果文件大于可用内存,则不可能实现这种处理。

.readline() 和 .readlines() 非常相似。它们都在类似于以下的结构中使用:

Python .readlines() 示例

fh = open('c:\\autoexec.bat')

for line in fh.readlines():

print line

.readline() 和 .readlines() 之间的差异是后者一次读取整个文件,象 .read() 一样。.readlines() 自动将文件内容分析成一个行的列表,该列表可以由 Python 的 for ... in ... 结构进行处理。另一方面,.readline() 每次只读取一行,通常比 .readlines() 慢得多。仅当没有足够内存可以一次读取整个文件时,才应该使用 .readline()。

3.split方法:

http://www.w3cschool.cc/python/att-string-split.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值