-2

I have a text file, the first two columns of which has alphanumeric values. I want to store them in a variable and print it afterwards. Can anyone tell me how to do so in Python? I tried using this

x2=np.loadtxt('iau1.txt', unpack=True, usecols=[0])

and then within a forloop:

for i in range(0, len(x2)-1): f1.write("%s" %(x2[i]))

iau1.txt ab12 98ji ab13 98jj . . .

Lekha
  • 1
  • 3

1 Answers1

1

As an alternative to using NumPy, you could also use the standard Python CSV library as follows:

import csv

# Load all rows from the file into a variable called rows
with open("iau1.txt", "r") as f_input:
    csv_reader = csv.reader(f_input, delimiter=" ", skipinitialspace=True)
    rows = list(csv_reader)

# Write the first two columns back to a different file and display it
with open("iau1_out.txt", "wb") as f_output:
    csv_writer = csv.writer(f_output, delimiter=" ")

    for cols in rows:
        csv_writer.writerow(cols[:2])
        print cols[0], cols[1]

Assuming an input file with the following format:

ab12 98ji 111 222 333 444
ab13 98jj aaa bbb ccc ddd

The output file will have:

ab12 98ji
ab13 98jj

Tested using Python 2.7.

Note, reading a the whole file into memory is usually fine for small files, but if your file is large you might want to consider processing this a line at at time as follows:

with open(r"iau1.txt", "r") as f_input, open(r"iau1_out.txt", "wb") as f_output:
    csv_reader = csv.reader(f_input, delimiter=" ", skipinitialspace=True)
    csv_writer = csv.writer(f_output, delimiter=" ")

    for cols in csv_reader:
        csv_writer.writerow(cols[:2])
        print cols[0], cols[1]
Martin Evans
  • 45,791
  • 17
  • 81
  • 97