For the SO admin/mods.
This question was marked closed as a duplicate to this question: How to read a file line-by-line into a list?
What a hoot. That isn't related to this question EXCEPT that it also involves a list. Didja bother to read the question?
Python 3 and 2.7.8.
I have a script that gets parsed into chunks based on the existence of a keyword. The argv after keyword is the file to process. All arguments up to the keyword are put into a list (inp_to_process). All files are simple ascii and are located in the current folder.
I want to open the files contained in the list, and my script fails. I am doing the same thing to open the file specified after the keyword, so I assume my issue has to do with using list elements as arguments.
I'm not able to do m for in list, nor can I use a range - both throw an exception trying to open the files given.
This single one works: try: with open(f_target) as FT: content_target = [line.rstrip('\n') for line in FT] except: # currently seems to print the parens too..
print ('Error! Unable to open file', f_target)
exit()
Here's the chunk of code doing the work (currently broken) both methods:
for x in range(0, len(inp_to_process)):
print (inp_to_process[x])
try:
with open (inp_to_process[x], "t") as d_input:
data = d_input.read()
print (len(data))
except:
print ('Error processing input file ' + inp_to_process[x])
exit()
and
for m in inp_to_process:
ifile = m
try:
print ('trying: ' + ifile)
with open (ifile, "t") as d_input:
print ('after open()')
data = d_input.read()
print (len(data))
# content = [line.rstrip('\n') for line in d_input]
# if not content in all_inp:
# all_inp.add(content)
except:
print ('Error processing input file ' + m)
So how can I access the list elements such they work in the open file command??
Thanks!