PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, August 19, 2022

[FIXED] When importing path from .env file I get two extra brackets added everywhere in the path variable?

 August 19, 2022     csv, dictionary, environment-variables, python     No comments   

Issue

PATH_OLD = r'C:\Users\Bilal\Python\Task1\OlderVersionFiles\' in my .env file. I get the following:

"r'C:\\\\Users\\\\Bilal\\\\Python\\\\Task1\\\\OlderVersionFiles\\\\'"

instead of

r'C:\\Users\\Bilal\\Python\\Task1\\OlderVersionFiles\\'

on running the following code:

import os
from dotenv import load_dotenv
load_dotenv()
result = os.getenv("PATH_OLD")
#Prints the correct path here
print(result)
dir_A_dict = dict()
directory_A = result
dir_A_files= [os.path.join(directory_A, x) for x in os.listdir(directory_A) if '.csv' in str(x)]

Gives the following error:

dir_A_files= [os.path.join(directory_A, x) for x in os.listdir(directory_A) if '.csv' in str(x)]
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: "r'C:\\\\Users\\\\Bilal\\\\Python\\\\Task1\\\\OlderVersionFiles\\\\'"

Solution

You're feeding os.listdir a string that is not a valid directory name, so it complains. You're trying to be too clever with your environment variable, it shouldn't be Python syntax. Just be simple:

PATH_OLD = C:\Users\Bilal\Python\Task1\OlderVersionFiles\


Answered By - Mark Ransom
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing