squidwardtenticles
squidwardtenticles

Reputation: 57

Why can't I open this file for reading in python?

I'm working in Python and I'm confused why I can't open the file I'm trying to. The code is pretty simple. Here it is.

import os
def main():
  FILE_NAME = "default_template.csv"
  source_path = os.path.join("Documents", FILE_NAME)
  file = open(source_path, "r")

At this point I get

IOError: [Errno 2] No such file or directory: 'Documents/FILE_NAME'.

I also decided to try to change directories for whatever reason using os.chdir() and passing just about every high level directory on my computer in seperately and nothing worked. In an attempt to find the fix for opening a file I tried editing the path in a bunch of different ways.

I've tried something like:

os.path.join("/derek/Documents", FILE_NAME)

os.path.join("/Documents", FILE_NAME)

os.path.join("~/derek/Documents", FILE_NAME)

os.path.join("~", FILE_NAME)

If anyone could help me out I would be extremely thankful. I'm still new to using python to navigate and manage files.

Upvotes: 0

Views: 116

Answers (1)

Pavel Reznikov
Pavel Reznikov

Reputation: 3208

Python doesn't expand ~ by default. To make it work try os.path.expanduser:

On Unix and Windows, return the argument with an initial component of ~ or ~user replaced by that user‘s home directory.

source_path = os.path.join("~/Documents", FILE_NAME)
source_path = os.path.expanduser(source_path)

Upvotes: 1

Related Questions