Full Problem: I have a text file that is made of different sequences on each line, I need to print to the user specifict lines individually.
File Example:
title(line1) ywzcywczywwyczwyczwyczywwwyzczczyw(line2) title2(line3) yxzwyxzwyxwyxzwywyxzwyxwyxzwy(line4) title3(line5) ywzxywxzywywxzywxywyzxywxz(line6) --In this example, I would need to print lines 2,4, and 6 to the user but one by one. (meaning I don't want to print all those lines at once.)
I have the following code to read the file: f = open("File.txt", "r") #open file and "r" is to read the file
I was thinking of reading the file and creating two different lists (One that will include all the titles as individual elements of the list and another one that will include all the "sequences"(ywxzwyzyxw) as individual element of the list, and then somehow printing each element of the desired list Individually, (instead of printing all the list at ones)
I'm new to python so I'm looking for example code that would help me tackle this problem. Thank you!!
CodePudding user response:
If you have some kind of pattern you may use,
with open(filename) as file:
lines = file.readlines()
for i, line in enumerate(lines): #i is the index for every element.
if i % 2 == 1:
continue
else:
print(line)
In this example, we are just going to print the lines like 0,2,4,6 etc.
CodePudding user response:
You should think if a pattern to determine the titles like . title or x title or 1. title etc. Then you can use if else statement to identify the title.
file:
.title1
sequence1
.title2
sequence2
code:
with open("file.txt", "r") as f:
all_lines = f.readlines()
titles = []
sequences = []
for line in all_lines:
if "." in line[0]:
titles.append(line.rstrip("\n"))
all_lines.remove(line)
for lines in all_lines:
sequences.append(lines.rstrip("\n"))
print(titles)
print(sequences)
You can also use caharacter numbers to identify. Like if every title is less than 8 characters long and the sequences are much longer then you can use the len() function the determine if the line is title or not.
file:
title1
sequence1
title2
sequence2
code:
with open("file.txt", "r") as f:
all_lines = f.readlines()
titles = []
sequences = []
for line in all_lines:
if len(line)<8:
titles.append(line.rstrip("\n"))
all_lines.remove(line)
for lines in all_lines:
sequences.append(lines.rstrip("\n"))
print(titles)
print(sequences)
Then to print each element of the desired list individually:
for elements in titles:
print(elements)
or
for elements in sequences:
print(elements)