My input file has two columns. I am trying to print the second column of inputdata1.txt
within a second for-loop. But my code is not working. Can someone tell me what should I do?
Python3. In this method we will import the csv library and open the file in reading mode, then we will use the DictReader() function to read the data of the CSV file. This function is like a regular reader, but it maps the information to a dictionary whose keys are given by the column names and all the values as keys.
with open('inputdata1.txt') as inf:
for line in inf:
parts = line.split() # split line into parts
if len(parts) > 1: # if at least 2 parts/columns
print parts[1] # print column 2
This assumes the columns are separated by whitespace.
Function split() can specify different separators. For instance if the columns were separated with commas ,
you'd use line.split(',')
in the code above.
NOTE: Using with
to open your file automatically closes it when you are done, or if you encounter an exception.
You could do something like this. Separator
is the character your file uses to separate colums, e.g. tabs or commas.
for line in open("inputfile.txt"):
columns = line.split(separator)
if len(columns) >= 2:
print columns[1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With