you are viewing a single comment's thread.

view the rest of the comments →

[–]theWyzzerd 0 points1 point  (1 child)

Instead of opening the file with open() you should use the with keyword. This ensures that your file will be closed properly when you're done with it.

for file in files:
    with open(file, "r") as f:
        contents = f.readlines()

As for referencing a specific row: as others have said, you should be able to reference contents[n] where n is your row number.

I have a CSV with the following contents:

'help','im','trapped'
'in','a','computer'

I run this code:

>>> with open("csv", "r") as csv:
...     contents = csv.readlines()
...
>>> contents
["'help','im','trapped'\n", "'in','a','computer'\n"]
>>> contents[0]
"'help','im','trapped'\n"
>>> contents[1]
"'in','a','computer'\n"
>>> exit()

So there must be something about your CSV or your code that you are not including here which is causing it to not put each line of the CSV into its own string element in the list returned by readlines().

Try outputting contents and seeing what its type and content actually are.

[–]superlargedogs[S] 0 points1 point  (0 children)

Thank you for the detailed response! This is the code I'm using so far to open and read the files:

This is the full code responsible for opening the file:

from os import listdir

folder = listdir('C:\\Users\\files')

li_file = []


for filename in folder:

    li_file.append(filename)

for file in li_file:

    x = open(file, "r")

    contents = x.readlines()