0

How do I find an empty line, in a CSV file, that looks like this ',,,,,,,,,,,,,,,,,,\n' with python's ReadLine().

I want to write something like this:

file = 'file.csv'

f = open(file, mode='r', encoding='utf8')

while f.readline() != '\n' or f.readline() != ',,,,,,,,,,,,,,,,,,\n':
    pass

df = pd.read_csv(f, header=None)

f.close()

The or f.readline() != ',,,,,,,,,,,,,,,,,,\n': is not identifying the line that looks like this ',,,,,,,,,,,,,,,,,,\n'

I felt that would work when running f.readline() manually in my notebook over and over until I got to the first "blank" line. Then the output looked like ',,,,,,,,,,,,,,,,,,\n' and I thought surely that would pick it up. Needless to say it did not.

2
  • What does the top of your CSV look like, with all the empty lines and ,,,,,,,,,,,,,,,,,, lines? Commented Apr 25, 2022 at 18:23
  • @ZachYoung The file has a few lines at the top. Those lines contain strings, then the end of each line contains commas ,,,,,,,,,,,,,, random. You'll see I have accepted the answer but I still don't understand these additional commas. Commented Apr 26, 2022 at 19:51

1 Answer 1

2

By calling f.readline() twice in that or statement, you're actually processing two lines. Try storing it as a variable before evaluating it, so you only process one line at a time. Does this do what you need?:

import pandas as pd

file = 'file.csv'

f = open(file, mode='r', encoding='utf8')

if_continue = True
while if_continue:
    current_line = f.readline()
    print(f"current_line is {current_line}")
    if current_line != '\n' or current_line !=  ',,,,,,,,,,,,,,,,,,':
        if_continue = False
        print("Exiting while loop")

df = pd.read_csv(f, header=None)

f.close()
Sign up to request clarification or add additional context in comments.

1 Comment

hey thanks! unfortunately no. while f.readline() not in (',,,,,,,,,,,,,,,,,,\n', '\n'): solves the problem. I did learn about this from your response though! It led to new questions!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.