I want to read a csv file without using the open()
function.
file.txt
'xxr'|'wer'|'xxr'|'xxr'
'xxt'|'dse'|'xxt'|'xxt'
'xxv'|'cad'|'xxv'|'xxv'
'xxe'|'sdf'|'xxe'|'xxe'
'xxw'|'sder'|'xxw'|'xxw'
'xxz'|'csd'| 'xxz'| 'xxz'
I've tried this, but this don't open a file, just use 'file.txt' as string.
file = ('file.txt')
reader = csv.reader(file,delimiter="|")
mylist = list(reader)
I CANNOT use the regular with open('file.txt', 'r')
....
Reason: The customer is sending this data pipeline to a platform that doesn't support open() function, due to directory function restrictions (not permission issue).
I also cannot read as Dataframe because are unstructured lists, this template is very simplier.
Any ideas?
CodePudding user response:
You could use fileinput
although I'm unsure of how the module deals with opening the files and if it is any different than the open
function but it does allow for multiple files to be opened in order using one stream and it seems to allow for more flexibility in how the file is read:
import fileinput
with fileinput.input('file.txt') as f:
reader = csv.reader(file,delimiter="|")
mylist = list(reader)
CodePudding user response:
What's wrong with:
reader = csv.reader(open(file),delimiter="|")
Or with pandas
:
import pandas as pd
mylist = pd.read_csv(file, sep="|").to_numpy().tolist()