简体   繁体   中英

Python writes 0 to the file

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.

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM