I'm facing a problem in coding the file management part of my algorithm.
The aim of my file manager is to take a source file, then read it line by line, and split each line in a new file according to filters.
Data are separated with tabulation \t
.
The filter consist of gathering all lines with same 4rth parameters ( you can say it is ordering them).
My problem is that I want to have dynamic file-names according to that parameters, which is an integer.
So the main file will be filled with a part of the algorithm like this:
Logfile.write("%s\t %s\t %s\t %s\t %s\t %s\n" % (count, BSid, UEid, nbr_RB, Metric,))
the nbr_RB
will be my filter parameters, it is a random set of integer ranging 1 to 100.
what I want to do is to automate this code:
open('/usr/local/resultat/file_1', 'w') # here 1 is linked to the nbr_RB[i]
open('/usr/local/resultat/file_2', 'w')
.
.
.
open('/usr/local/resultat/file_nbr_RB[i]', 'w')
so each time will have the nbr_RB[i]
in the file name, I'm not writing 100 lines .
And when I will apply the filter:
ligne = Logfile.split(“\n”)
par = ligne.split(“\t”)
if par [3] = nbr_RB[1]:
file_nbrRB[1].write (“%s \n” % (ligne))
elif par [3] = nbr_RB[4]:
file_nbrRB[4].write (“%s \n” % (ligne))
.
.
.
elif par [3] = nbr_RB[i]:
file_nbrRB[i].write (“%s \n” % (ligne))
I have looked some solution and found this :
For Python versions prior to 2.6, use the string formatting operator %:
filename = "ME%d.txt" % i
For 2.6 and later, use the str.format() method:
filename = "ME{0}.txt".format(i)
Though the first example still works in 2.6, the second one is preferred.
If you have more than 10 files to name this way, you might want to add leading zeros so that the files are ordered correctly in directory listings:
filename = "ME%02d.txt" % i
filename = "ME{0:02d}.txt".format(i)
This will produce file names like ME00.txt to ME99.txt. For more digits, replace the 2 in the examples with a higher number (eg, ME{0:03d}.txt).
And :
import os, sys
path = "c:/temp"
for filename in ["chas.txt", "dave.txt"]:
f = open (os.path.join (path, filename))
print filename
print f.read ()
print
f.close ()
Edit: I think I really badly explained my problem, here is what i coded for the first log file, before any treatment:
logfile= open('/usr/local/Python-3.3.0/my_tests/fichier_log/logfile_%s_%s.txt' %c %z , 'a')
and here is the error:
Traceback (most recent call last):
File "/usr/local/Python-3.3.0/my_tests/log_files.py", line 181, in <module>
main()
File "/usr/local/Python-3.3.0/my_tests/log_files.py", line 167, in main
logfile= open('/usr/local/Python-3.3.0/my_tests/fichier_log/logfile_%s_%s.txt' %c %z , 'a')
TypeError: not enough arguments for format string