简体   繁体   English

Python将0写入文件

[英]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. 我正在尝试将os.system函数返回的数据写入文件。 But the only thing that gets written in file is 0. Here are some other variations that I tried as well. 但是唯一要写入文件的是0。这也是我尝试过的其他一些变化。

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. 我也尝试过使用return但没有用。 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 . 退出代码为零,但内容将在out.txt

For windows (I assume you are using Windows since you are using the 'dir' command, not the Unix/Linux 'ls'): 对于Windows(我假设您正在使用Windows,因为您使用的是“ dir”命令,而不是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. 我喜欢使用子流程的其他解决方案,但是由于无论如何这都是特定于OS的,因此我认为这更简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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