I am new to programming and having some problem figuring out nested loops. I have a list of data that I want to extract from a larger file. I am able to extract one item of data from the larger file successfully but I need to extract 100 different trials from this larger file of thousands of trials. Each trial is one line of data of the larger file. This is the program I have used to extract one line of data successfully one at a time. In this example it extracts the data for trial 1. It is based off of examples I have seen in prior questions and tutorials. The problem is that I don’t need trials 1-100, or any ordered pattern. I need trials 134, 274, 388, etc. It skips around. So I don’t know how to do a nested loop using the for statement if it doesn’t have a range that I can enter. Any help is appreciated. Thanks.
completedataset = open('completedataset.txt', 'r')
smallerdataset = open('smallerdataset.txt', 'w')
for line in completedataset:
if 'trial1' in line: smallerdataset(line)
completedataset.close()
smallerdataset.close()
I’d really like to do it like this:
trials = (‘trial12’, ‘trial23’, ‘trial34’)
for line in completedataset:
for trial in trials:
if trial in line: smallerdataset(line)
but this isn’t working. Can anyone help me modify this program so that it works correctly?
You are going to run into some problems with the way you are specifying your trials. If you look for lines containing ‘trial1’, you will also get lines containing ‘trial123’. If you larger dataset is structured in some way you can trying looking for the trial number in a particular field. For instance, if the data is comma delimited you can make use of the csv package. Finally, using a generator expression instead of the loop will make things a little cleaner. Assuming that the trial number was in the first column of your dataset you could do something like: