2

I have a batch script on a local machine that calls a Python script on a Windows network share and should write a file there. If I run the Python script without the batch file, it runs successfully. If I run the batch file, I get this error:

Traceback (most recent call last):
File "python_script.py", line 25 in <module>
 IOError: [Errno 13] Permission denied: 'outfile.txt'

The Python script lives in the same directory as "outfile.txt".

Here is the code from the Python script:

outfile = open("outfile.txt", "w")    

I have also tried an absolute path, but I get an error that the "file is not found":

outfile = open("\\server\folder\subfolder\outfile.txt", "w")

I don't think it's a permission issue, because if I just run the python script "by hand" logged in as the same user, it writes the outfile to the network share. What am I missing using the batch file?

alig227
  • 327
  • 1
  • 6
  • 17

1 Answers1

4

When you "call" the python script, you are actually executing it from the current directory. Since I don't think you can cd to a network share without mapping it, this will probably cause a permission issue.

The absolute path will work but you just need to specify the path correctly. In python, the backslash is an escape character, so you either have to escape your backslashes or use forward slashes:

outfile = open("//server/folder/subfolder/outfile.txt", "w")

See Using Python, how can I access a shared folder on windows network?

Community
  • 1
  • 1
nullability
  • 10,545
  • 3
  • 45
  • 63
  • Thanks that worked @nullability, now it writes the outfile. But now I have a problem opening the input files. I am using the forward slashes, is this a limitation of os.listdir? `files = [file for file in os.listdir('//server/subfolder/folder') if os.path.isfile(file)] for file in files: if filename_pattern.search(file): print file` – alig227 Oct 01 '14 at 19:02
  • The absolute path to the directory I'm reading works when running the script manually. Again, when running the batch file it can't find the files to read. Strangely there is no error, it just writes an empty outfile. – alig227 Oct 01 '14 at 19:29
  • Can you show your batch file and how you are running it? – nullability Oct 01 '14 at 19:31
  • 2
    Actually you can use a raw-string so you don't have to escape backslashes: `outfile = open(r"\\server\folder\subfolder\outfile.txt", "w")`. Note the `r` at the beginning of the path string. – Mike Driscoll Oct 01 '14 at 21:21
  • the bat file contains one line: call "\\server\subfolder\folder\script.exe" (I compiled into an exe). I have a print statement that runs, so I know the program is running, but it writes a blank outfile. I may need to log a new question since I'm using os.listdir instead of Open – alig227 Oct 02 '14 at 14:07
  • I solved the read file issue. I just needed to enter an absolute path in the open() function, now it can open the files in the remote directory. – alig227 Oct 08 '14 at 17:21