Reputation: 2433
I am trying to open a .csv file from a network location and running into following error..i have the following questions
1.How to open a network location in windows
2.how to open the same network location in both windows and linux?
import csv
import datetime
from collections import deque
#from collections import maxlength
icount=9
now = datetime.datetime.now()
time =now.strftime("%m/%d/%Y")
#Keep appending date and count everytime this script is run
c = csv.writer(open("\\data\loc\\scripts\trend.csv", "ab"))
c.writerow([time, icount-1])
#Now read the recent 5 entries and print
#cr = csv.reader(open("trend.csv","rb"))
with open('trend.csv','rU') as fin:
reader=csv.reader(fin)
d=deque(reader,8)
for l in d:
print l[0]
print l[1]
Error:-
Traceback (most recent call last):
File "database.py", line 10, in <module>
c = csv.writer(open("\\data\loc\scripts\trend.csv", "ab"))
IOError: [Errno 2] No such file or directory: '\\data\loc\\scripts\trend.csv'
Upvotes: 2
Views: 8403
Reputation: 365925
Your first problem is here:
c = csv.writer(open("\\data\loc\\scripts\trend.csv", "ab"))
Because you're not escaping your backslashes, the \t
turns into a tab, each \\
turns into a single backslash, and with \l
you get lucky and it's unchanged. So, this is the path you're asking for:
\data\loc\scripts rend.csv
Obviously there's nothing there.
Always use raw strings for Windows paths, and you won't have this problem.
c = csv.writer(open(r"\\data\loc\\scripts\trend.csv", "ab"))
Assuming there's an SMB server named data
with a share named loc
and you're already logged in, this will now work.
You should still get rid of the extra backslash before scripts
, and always close files that you open… but neither of those is causing your problem.
From linux, you cannot access SMB shares with UNC paths like this.
There are two common ways around this.
First, you can mount the SMB share somewhere on your filesystem. If you've mounted smb://data/loc
to /mnt/data-loc
, all you have to write is this:
c = csv.writer(open(r"/mnt/data-loc/scripts/trend.csv", "ab"))
Alternatively, you can access SMB directly, sort of like dealing with an FTP server. If you search PyPI, you'll find a variety of Python libraries to make this easy. Many of them require the libsmbclient
library, the smbclient
tool, or something else you may not have installed, so make sure to read the requirements. Here's how you'd do it with one of those libraries:
import smbclient
smb = smbclient.SambaClient(server='DATA', share='LOC', domain='WORKGROUP',
username='me', password='swordfish')
smb.chdir('scripts')
with smb.open('trend.csv', 'rb') as f:
data = f.read()
sio = StringIO.StringIO(data)
c = csv.writer(sio)
c.writerow([time, icount-1])
with smb.open('trend.csv', 'wb') as f:
f.write(sio.getvalue())
smb.close()
Upvotes: 1