Reputation: 9
import os
fileHandle = open('booksNames.txt', 'r+')
def getData():
data = os.system('dir /b /a /s *.pdf *.epub *.mobi')
fileHandle.writelines(str(data))
fileHandle.close()
I'm trying to write the data returned by the os.system function to a file. But the only thing that gets written in file is 0. Here are some other variations that I tried as well.
import os
fileHandle = open('booksNames.txt', 'r+')
getData = lambda:os.system('dir /b /a /s *.pdf *.epub *.mobi')
data = getData()
fileHandle.writelines(str(data))
fileHandle.close()
On the output window, it gives perfect output but while writing to a text fileit writes zero. I've also tried using return but no use. Please Help.
Upvotes: 0
Views: 95
Reputation:
For windows (I assume you are using Windows since you are using the 'dir' command, not the Unix/Linux 'ls'):
simply let the command do the work.
os.system('dir /b /a /s *.pdf *.epub *.mobi >> booksNames.txt')
Using '>>' will append to any existing file. just use '>' to write a new file.
I liked the other solution using subprocess, but since this is OS-specific anyway, I think this is simpler.
Upvotes: 1
Reputation: 177600
Use the subprocess module. There are a number of methods, but the simplest is:
>>> import subprocess
>>> with open('out.txt','w') as f:
... subprocess.call(['dir','/b','/a','/s','*.pdf','*.epub','*.mobi'],stdout=f,stderr=f,shell=True)
...
0
Zero is the exit code, but the content will be in out.txt
.
Upvotes: 2