I try to read the file into pandas. The file has values separated by space, but with different number of spaces I tried:
pd.read_csv('file.csv', delimiter=' ')
but it doesn't work
I try to read the file into pandas. The file has values separated by space, but with different number of spaces I tried:
pd.read_csv('file.csv', delimiter=' ')
but it doesn't work
add delim_whitespace=True
argument, it's faster than regex.
delimiter=' '
as they are mutually exclusive in recent versions.
Aug 8, 2018 at 13:05
delimiter=' '
is very brittle, it says to expect one and only one space. No tabs, newsline, multiple spaces, nonbreaking whitespaces, combination of these etc. delimiter='\s+'
is what pandas recommends and is more robust.
you can use regex as the delimiter:
pd.read_csv("whitespace.csv", header=None, delimiter=r"\s+")
engine = "python"
to avoid a warning.
Mar 20, 2018 at 9:45
You can pass a regular expression as a delimiter for read_table also, and it is fast :).
result = pd.read_table('file', sep='\s+')
If you can't get text parsing to work using the accepted answer (e.g if your text file contains non uniform rows) then it's worth trying with Python's csv library - here's an example using a user defined Dialect:
import csv
csv.register_dialect('skip_space', skipinitialspace=True)
with open(my_file, 'r') as f:
reader=csv.reader(f , delimiter=' ', dialect='skip_space')
for item in reader:
print(item)