Home > Software design >  Python ReadLine() for CSV file
Python ReadLine() for CSV file

Time:04-25

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.

CodePudding user response:

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()

CodePudding user response:

while f.readline() not in (',,,,,,,,,,,,,,,,,,\n', '\n'):

  • Related