Using file uploaded to google’s Colab

In google colab i am using this code to submit a ephemeral file:

from google.colab import files
uploaded = files.upload()

Then i am using this code to read the file I just submited:

with open('edges.txt') as f:
    mylist = [line.rstrip('n') for line in f]
    newlist = []
    for line in mylist:
        line = line.split(',')             
        line[1], line[2] = line[2], line[1] 
        line = ','.join(line)               
        print(line)
        newlist.append(line)

What a I want is to use a generic name as uploaded in the with open(uploaded) line because not always the file’s name will be edges.txt.

Ho can I do this? I tried to use uploaded but it didn´t work.

Thanks

Answer

The name of the file as well as its contents will be in the uploaded variable, so there’s no need to read the file again after upload.

Here’s a full example:

enter image description here

The key bit is the for name, contents in f.items() line. files.upload returns a dict, with keys corresponding to the file names of items selected in the file picker. Dict values are the file contents.