I’m using csv files to store the large number of variables I need for my program. I use os.path to define the relative path to the two files and send those paths to a function called get_csv_args that opens the csv and parses the information. The first path opens fine, but the second path causes an error because the backslashes have all been doubled in the path. I tried using os.path.normpath but it didn’t help.
Main function
import os
from misc.get_csv_args import get_csv_args
def main():
server=os.path.abspath('..\..\server_info.csv')
archive=os.path.abspath('.\CreateDelete_archive_info.csv')
print server
print archive
print str(get_csv_args(server))
print str(get_csv_args(os.path.normpath(archive)))
if __name__ == '__main__':
main()
get_csv_args
import csv, os.path
def get_csv_args(filename):
read_args = csv.reader(open(os.path.normpath(filename), 'rb'))
args = []
for row in read_args:
args = args + row[:2] #Add the first two items in each row to the args list
args = filter(lambda name: name.strip(), args) #Remove whitespace entries from the list
return args
Main Output
C:\Users\blahblahblah\src\server_info.csv
C:\Users\blahblahblah\src\test_cases\archive\CreateDelete_archive_info.csv
[‘server’, ‘server_name’, ‘UID’, ‘user’, ‘PWD’, ‘password’]
Traceback (most recent call last):
blahblahblah
IOError: [Errno 2] No such file or directory: ‘C:\\Users\\blahblahblah\\src\\test_cases\\archive\\CreateDelete_archive_info.csv’
The backslashes being doubled is normal behavior, and is not causing your error – it happens because backslash is an escape character (eg,
'\t'is a tab, but'\\t'is a backslash followed by a ‘t’). This may cause you actual problems down the track, though (eg, a file called ‘.\thing’ will cause horrible breakage), so you should use forward slashes or raw strings for paths.The most likely thing to be causing your current problem is that the file CreateDelete_archive_info.csv actually doesn’t exist. Make sure you have the name and path right – eg, in a command prompt, do: