Search code examples
pythonpython-3.xgoogle-colaboratorypython-os

Does path function work differently in python IDLE and google colab?


I have a code which perfectly works when executed in IDLE buts the same piece of code shows error when executed in google colab.

code snippet:

im_path = os.path.join('D:\ANIKET\movie data set sentiment analysis','aclImdb')
train_texts = []
train_labels = []

for category in ['pos','neg']:
    train_path = os.path.join(im_path,'train',category)
    for fname in sorted(os.listdir(train_path)):
        if fname.endswith('.txt'):
            with open(os.path.join(train_path, fname),encoding = 'utf8') as f:
                train_texts.append(f.read())
            train_labels.append(0 if category == 'neg' else 1)

colab error:

FileNotFoundError                         Traceback (most recent call last)
<ipython-input-3-9c42cfcaed98> in <module>()
     19     train_path = os.path.join(im_path,'train',category)
     20 
---> 21     for fname in sorted(os.listdir(train_path)):
     22         if fname.endswith('.txt'):
     23 

FileNotFoundError: [Errno 2] No such file or directory: 'D:\\ANIKET\\movie data set sentiment analysis/aclImdb/train/pos'

Solution

  • Unless you set up a local runtime, colab codes run on Google's server, which is likely running on a Linux environment, and it doesn't have access to your local files.

    You either need to upload these files to the server first (and adjust the file path) or you'd need to set up local runtime.