Mike Ralston Mike Ralston - 1 year ago 170
Python Question

Iterate through lines and write into a new file based on certain row criteria

What I'm trying to do is read for a specific value from a column in a CSV and write its corresponding row into a new file in python. I am able to write every row successfully into a new .txt file, but I am having trouble writing only the specific row(s) into the new file.

The data looks as follows:

card_no items qty price
10001 carrot 3 15.50
10002 squash 5 12.68
10003 pear 5 13.50

Here is the code that reads in the zip file (a single .csv is contained inside) and iterates over each row / writes the rows into the new txt file.

import os
import zipfile

with open(working_directory + "crash_test.txt",'w') as ofile :
with zipfile.ZipFile('/Users/MikeRalston/Desktop/testArchive2.zip') as z:
for filename in z.namelist():
if not os.path.isdir(filename):
with z.open(filename) as f:
for idx, line in enumerate(f.readlines()) :
###if "card_no" == int(10001):
line = line.decode('UTF-8').split (",")

ofile.write("\t".join(line) + "\n")

The 'if' statement is where I believe I am messing up.

Answer Source

Since you are not reading headers separately, you can't use if "card_no" ==

All we are getting from reading file as text is a line. Once we split , we get a list of columns separated by commas. Now we can use first column using line[0] and use that value for comparison.

Here we are comparing is value of line[0] is a digit and equal to 1001.

After ###if "card_no" == int(10001):
Use following,

line = line.decode('UTF-8').rstrip().split ()
if line[0].isdigit() and line[0] == '10001':
    ofile.write("\t".join(line) + "\n")

Contents of ofile

10001 carrot 3 15.50

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download