I have 2 codes which did the same work as which i am asking , but still i didn't get any useful or better code for my data set to make it useful for me , First let me clear what i am doing .
I have 2 TEXT
files , one name as input_num
and second named as input_data
as it is clear from names that input_num.txt
have number in them , and input_data
have data in it , these 2 files are of 8 to 10 mb , let me show you some of their part ,
This is 'input_num.txt'
ASA5.txt DF4E6.txt DFS6Q7.txt
and this input_data.txt
>56|61|83|92|ASA5
Dogsarebarking
These 2 are some parts of their text files , input_data.txt
have last column which contain ASA5
and so on , these are data from input_num.txt
, so the program first check the last column of >56|61|83|92|ASA5
which is ASA5
than goto input_num.txt
which have 5
, it contain some value in input_num.txt
like 4
in the above , so it come back to the input_data.txt
goto the words and cut them to 4 ,
I have 2 codes for it : 1 is
import os
import re
file_c = open('num_data.txt')
file_c = file_c.read()
lines = re.findall(r'\w+\.txt \d+', file_c)
numbers = {}
for line in lines:
line_split = line.split('.txt ')
hash_name = line_split[0]
count = line_split[1]
numbers[hash_name] = count
file_i = open('input_data.txt')
file_i = file_i.read()
for hash_name, count in numbers.iteritems():
regex = '(' + hash_name.strip() + ')'
result = re.findall(r'>.*\|(' + regex + ')(.*?)>', file_i, re.S)
if len(result) > 0:
data_original = result[0][2]
stripped_data = result[0][2][int(count):]
file_i = file_i.replace(data_original, '\n' + stripped_data)
f = open('input_new.txt', 'wt')
f.write(file_i)
f.close()
and the 2nd is
import csv
output = open('output.txt' , 'wb')
def get_min(num):
return int(open('%s.txt' % num, 'r+').readlines()[0])
last_line = ''
input_list = []
#iterate over input.txt in sort the input in a list of tuples
for i, line in enumerate(open('input.txt', 'r+').readlines()):
if i%2 == 0:
last_line = line
else:
input_list.append((last_line, line))
filtered = [(header, data[:get_min(header[-2])] + '\n' ) for (header, data) in input_list]
[output.write(''.join(data)) for data in filtered]
output.close()
csv
because you feel comfortable with it… you're not actually usingcsv
at all. You doimport
it in one case, but you never touch it. You use a regex in one program, and apparently use complete lines without even attempting to split into columns in the other.readlines()
calls. There is almost never a reason to usereadlines()
. If you just dofor i, line in enumerate(f)
, it gives you one line at a time, buffering as efficiently as possible; if you dofor i, line in enumerate(f.readlines())
, it first reads and parses the entire file in memory, and only then gives you one line at a time. This is never helpful, and often a problem.input_num.txt
into number of text files , and than it again stop working when some text file which is not numeric name appear , likeEOG6003RW