Question

I am unable to open any CSV file produced by a program(I don't have full details of program), it comes out with file names like 266925.130314-88850999.word

The file is a csv, it opens in excel 2013 and all editors fine, I have tried opening with original file name, I have tried opening by changing extension from .word to .csv

Nothing works, I get the errors detailed below.

Sample Part of CSV

"tes","","2PT26","",4,7,"TEST","SHEEP AND STUFFF                  1kg","",1.1111,9.9999,1,0.000,2.6900,0.0000,0.000,

Full error Message in idle gui

>>> open('C:\Console2\edz\test.csv', 'r', newline='', encoding='utf-8')
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
open('C:\Console2\edz\test.csv', 'r', newline='', encoding='utf-8')
OSError: [Errno 22] Invalid argument: 'C:\\Console2\\edz\test.csv'

Pandas error (not given full because its massive amount of text with traceback - can add if required)

OSError: File b'C:\\Console2\\edz\test.csv' does not exist

I have tested this file exists with

files = os.listdir("C:\Console2\edz")
print (files)

['report.csv', 'test.csv']

I can use EXACT same code with report.csv (this csv is a known working one not created by program) and it loads fine.

I do not understand why this file wont open, I have tried open/read_csv/read_excel, all produce same errors on both idle and pandas.

Pulling my hair out, please assist.

Was it helpful?

Solution

The issue here is that Python uses escapes in strings - '\t' is a tab character, so when that sequence appears in your path, it changes meaning (note how in the output, the other backslashes have been escaped). Python is looking for 'C:\Console2\edz est.csv'.

The best solution is to use forward slashes for paths - Python will do the correct thing, even under Windows.

open('C:/Console2/edz/test.csv', 'r', newline='', encoding='utf-8')

You can also use a raw string (r'C:\Console2\edz\test.csv') or escape your backslashes ('C:\\Console2\\edz\\test.csv') - but the former can't deal with trailing backslashes, and the latter is hard to read and write.

OTHER TIPS

\t is an escape character in python, try \\t.

C:\\Console2\\edz\\test.csv

you can also prefix the string with r 'raw string' before the path (r'C:\Console2\edz\test.csv'','r')

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top