Iterate file name with counter - python

I'm splitting a file based on a string, and would like to have the output file names be numbered.
This is what I have so far:
outputfile = open("output.seq")
outputfileContent = outputfile.read()
outputfileList = outputfileContent.split(">")
for count, line in enumerate(f):
for items in outputfileList:
seqInfoFile = open('%f.dat', 'w')
seqInfoFile.write(str(items))
I'm not sure where to define f.
Thanks for any help!

Assuming I haven't misunderstood you, where you have it.
outputfile = open("output.seq")
outputfileContent = outputfile.read()
outputfileList = outputfileContent.split(">")
for count, content in enumerate(outputfileList, 1):
with open("output_%s.dat" % count, "w") as output:
output.write(content)

It would seem that if you want to associate every item in the output file list with a file titled as its index, you should do something like this:
for i in range(len(outputfileList)):
seqInfoFile = open(str(i) + '.dat', 'w')
seqInfoFile.write(str(outputfileList[i]))
It's not quite as elegant as an iterator, but the other option is to determine the number by making a call to outputfileList.index(items) each time.

Open output.seq, write its first line (splitted at >) into the file 1.dat, the second one to 2.dat and so on:
with open("output.seq") as fi:
for count, line in enumerate(fi, 1):
with open('{0}.dat'.format(count), 'w') as fo:
fo.writelines(line.split('>'))

Related

How can I print the lines from the text file next to random generated numbers

The text file is "ics2o.txt" and I don't know how to print numbers next to the lines
import random
print ("----------------------------------------------------------")
print ("Student Name Student Mark")
print ("----------------------------------------------------------")
f = open("ics2o.txt")
for line in f:
x = len(f.readlines())
for i in range (x):
contents = f.read()
print(str(contents) + str(random.randint(75,100)))
for line in f:
x = len(f.readlines())
for i in range (x):
contents = f.read()
print(str(contents) + str(random.randint(75,100)))
The problem is that you are reading the file in at least 3 different ways which causes none of them to work the way you want. In particular, f.readlines() consumes the entire file buffer, so when you next do f.read() there is nothing left to read. Don't mix and match these. Instead, you should use line since you are iterating over the file already:
for line in f:
print(line + str(random.randint(75,100)))
The lesson here is don't make things any more complicated than they need to be.
Firstly, doing print("----...") is a bad practice, at least use string multiplication:print("-"*10)
Secondly, always open files using 'with' keyword. (u can google it up why)
Thirdly, the code:
with open("ics2o.txt") as f:
for i,j in enumerate(f):
print(i,j)

Read in every line that starts with a certain character from a file

I am trying to read in every line in a file that starts with an 'X:'. I don't want to read the 'X:' itself just the rest of the line that follows.
with open("hnr1.abc","r") as file: f = file.read()
id = []
for line in f:
if line.startswith("X:"):
id.append(f.line[2:])
print(id)
It doesn't have any errors but it doesn't print anything out.
try this:
with open("hnr1.abc","r") as fi:
id = []
for ln in fi:
if ln.startswith("X:"):
id.append(ln[2:])
print(id)
dont use names like file or line
note the append just uses the item name not as part of the file
by pre-reading the file into memory the for loop was accessing the data by character not by line
for line in f:
search = line.split
if search[0] = "X":
storagearray.extend(search)
That should give you an array of all the lines you want, but they'll be split into separate words. Also, you'll need to have defined storagearray before we call it in the above block of code. It's an inelegant solution, as I'm a learner myself, but it should do the job!
edit: If you want to output the lines, simply use python's inbuilt print function:
str(storagearray)
print storagearray
Read every line in the file (for loop)
Select lines that contains X:
Slice the line with index 0: with starting char's/string as X: = ln[0:]
Print lines that begins with X:
for ln in input_file:
if ln.startswith('X:'):
X_ln = ln[0:]
print (X_ln)

Replace keys with values and write in a new file Python

I've got a problem trying to replace keys (dictionary) that I have in a file, with its corresponding values. More details: an input file called event_from_picks looks like:
EVENT2593
EVENT2594
EVENT2595
EVENT41025
EVENT2646
EVENT2649
Also, my dictionary, created by reloc_event_coords_dic() looks like:
{'EVENT23595': ['36.9828 -34.0538 138.1554'], 'EVENT2594': ['41.2669 -33.0179 139.2269'], 'EVENT2595': ['4.7500 -32.7926 138.1523'], 'EVENT41025': ['16.2453 -32.9552 138.2604'], 'EVENT2646': ['5.5949 -32.4923 138.1866'], 'EVENT2649': ['7.9533 -31.8304 138.6966']}
What I'd like to end up with, is a new file with the values instead of the keys. In this case, a new file called receiver.in which will look like:
36.9828 -34.0538 138.1554
41.2669 -33.0179 139.2269
4.7500 -32.7926 138.1523
16.2453 -32.9552 138.2604
5.5949 -32.4923 138.1866
7.9533 -31.8304 138.6966
My wrong function (I know I must have a problem with loops but I can't figure out what) so far is:
def converted_lines ():
file_out = open ('receiver.in', 'w')
converted_lines = []
event_dict = reloc_event_coords_dic()
data_line = event_dict.items() # Takes data as('EVENT31933', ['10.1230 -32.8294 138.1718'])
for element in data_line:
for item in element:
event_number = element[0] # Gets event number
coord_line = event_dict.get (event_number, None)
with open ('event_from_picks', 'r') as file_in:
for line in file_in:
if line.startswith(" "):
continue
if event_number:
converted_lines.append ("%s" % coord_line)
file_out.writelines(converted_lines)
Thanks for reading!
just do the following:
with open('receiver.in', 'w') as f:
f.writelines([v[0] for v in reloc_event_coords_dic().itervalues()])
Your first loop just leaves the last pair in the coord_line variable.
Better do
event_dict = reloc_event_coords_dic()
with open ('event_from_picks', 'r') as file_in:
with open('receiver.in', 'w') as file_out:
for in_line in file_in:
file_out.writelines(event_dict[in_line.strip()])
(untested, but you should get the logic).

Python: How to know the number of row of a text file

I want to know the number of row of a text file.
How can I do this?
if iterating over a file:
for line_no, line in enumerate(f, start=1):
or if counting the lines in a file (f):
count = sum( 1 for line in f )
f = open('textfile.txt', 'rb')
len(f.readlines())
readlines() method returns a list where each index holds a line of textfile.txt.
f = open("file.text")
count = sum(1 for line in f)
which is equivalent to
count = 0
for line in f:
count+=1
As #Dan D. said, you can use enumerate() on the open file. The default is to start counting with 0, so if you want to start the line count at 1 (or something else), use the start argument when calling enumerate(). Also, it's considered poor practice to use "file" as a variable name, as there is a function by that name. Thus, try something like:
for line_no, line in enumerate(open(file_name), start=1):
print line_no, line

Read a multielement list, look for an element and print it out in python

I am writing a python script in order to write a tex file. But I had to use some information from another file. Such file has names of menus in each line that I need to use. I use split to have a list for each line of my "menu".
For example, I had to write a section with the each second element of my lists but after running, I got anything, what could I do?
This is roughly what I am doing:
texfile = open(outputtex.tex', 'w')
infile = open(txtfile.txt, 'r')
for line in infile.readlines():
linesplit = line.split('^')
for i in range(1,len(infile.readlines())):
texfile.write('\section{}\n'.format(linesplit[1]))
texfile.write('\\begin{figure*}[h!]\n')
texfile.write('\centering\n')
texfile.write('\includegraphics[scale=0.95]{pg_000%i.pdf}\n' %i)
texfile.write('\end{figure*}\n')
texfile.write('\\newpage\n')
texfile.write('\end{document}')
texfile.close()
By the way, in the inclugraphics line, I had to increace the number after pg_ from "0001" to "25050". Any clues??
I really appreciate your help.
I don't quite follow your question. But I see several errors in your code. Most importantly:
for line in infile.readlines():
...
...
for i in range(1,len(infile.readlines())):
Once you read a file, it's gone. (You can get it back, but in this case there's no point.) That means that the second call to readlines is yielding nothing, so len(infile.readlines()) == 0. Assuming what you've written here really is what you want to do (i.e. write file_len * (file_len - 1) + 1 lines?) then perhaps you should save the file to a list. Also, you didn't put quotes around your filenames, and your indentation is strange. Try this:
with open('txtfile.txt', 'r') as infile: # (with automatically closes infile)
in_lines = infile.readlines()
in_len = len(in_lines)
texfile = open('outputtex.tex', 'w')
for line in in_lines:
linesplit = line.split('^')
for i in range(1, in_len):
texfile.write('\section{}\n'.format(linesplit[1]))
texfile.write('\\begin{figure*}[h!]\n')
texfile.write('\centering\n')
texfile.write('\includegraphics[scale=0.95]{pg_000%i.pdf}\n' %i)
texfile.write('\end{figure*}\n')
texfile.write('\\newpage\n')
texfile.write('\end{document}')
texfile.close()
Perhaps you don't actually want nested loops?
infile = open('txtfile.txt', 'r')
texfile = open('outputtex.tex', 'w')
for line_number, line in enumerate(infile):
linesplit = line.split('^')
texfile.write('\section{{{0}}}\n'.format(linesplit[1]))
texfile.write('\\begin{figure*}[h!]\n')
texfile.write('\centering\n')
texfile.write('\includegraphics[scale=0.95]{pg_000%i.pdf}\n' % line_number)
texfile.write('\end{figure*}\n')
texfile.write('\\newpage\n')
texfile.write('\end{document}')
texfile.close()
infile.close()

Categories

Resources