0

My python code features a section which processes .pcap files into .csv files. Upon opening these files in excel, they are correctly formatted into cells, or if opened in a text editor, they are correctly formatted with "," delimiters.

However, when using csv.reader, the file's data is not correctly outputted. The code is here:

for file in os.listdir(__directory):
    if file.endswith(".csv"):
        csv_reader = csv.reader(open(file), delimiter=',')
        for row in csv_reader:
            print(row)

The text file contents contain source and destination IPs, as well as TTL values. print(row) oddly outputs the source and destination IPs, however not the TTL values. Also, the IPs are separated with a "'" instead of with a ",". And in some cases, the delimiter is outputted instead.

For example, when the text file may contain:

0.0.0.0,1.1.1.1,128

It may be outputted as

0.0.0.0'1.1.1.1

EDIT:

for file in os.listdir(__directory):
    if file.endswith(".csv"):
        with open(os.path.join(__directory, file)) as csv_file:
            csv_reader = csv.reader(csv_file, delimiter=',')
            for row in csv_reader:
                print(row)

This edit from the previous code outputs the desired results (as Ture mentioned in the comments). I am not sure why...

Rob Rorry
  • 51
  • 2
  • 5
  • 1
    That's odd. I can't seem to get any issue when reading a file with `0.0.0.0,1.1.1.1,128` as the only line in it using the same code you posted. – Sandil Ranasinghe Feb 20 '22 at 07:45
  • 3
    The csv reader returns lists, so you'd expect `print(row)` to print something like `['0.0.0.0', '1.1.1.1', 128]`, which it does, when I try it. This needs a reproducible example. – Ture Pålsson Feb 20 '22 at 07:50
  • Welcome back to Stack Overflow. As a refresher, please read [ask] and https://stackoverflow.com/help/minimal-reproducible-example. Make certain that you can verify the *exact* contents of the file, *possibly including unprintable characters*. Make certain that you know the *encoding* of the file, and that you specify the right encoding when opening the file. Using the data that you show does not allow any of us to reproduce the problem. – Karl Knechtel Feb 20 '22 at 08:06
  • The file is actually 101 lines in length, however I just gave an example of what one line looked like. I apologize for the confusion, I should have clarified myself on this and included a reproducable example. Regardless, I did edit my question, as I have resolved the issue - alhough quite frankly, I am not sure why the fix works. Any explaination on it would be appreciated. – Rob Rorry Feb 20 '22 at 10:15
  • Could it be that the first version simply opens the wrong file (because of the missing os.path.join)? This is why examples should be *complete* and *minimal*. There are too many unknowns, both in the first example and the "fixed" one, for an outsider to be able to tell what the difference is. – Ture Pålsson Feb 20 '22 at 10:42

0 Answers0