2016-04-22 85 views
1

我試圖在Python中使用Unix find命令,無法獲得輸入pwd`pwd`也無法正常工作。使用Unix查找`pwd`

import commands 
import os 

f = raw_input('Enter name of the file: ') 
fh = open(f, 'r') 

prevdir = os.getcwd() 
files = fh.readlines() 

for line in files: 
    os.chdir(line) 
    print commands.getoutput('find `pwd` -name "*.txt"') 
    # print commands.getoutput('find \`pwd\` -name "*.txt"') 
+0

您commands.getoutput線爲我工作。你在Python shell中試過嗎? – trans1st0r

+0

正如其他人所建議的那樣,Python中幾乎可以確定的方法可以完成您正在嘗試執行的任務 - 例如, 'os.listdir','os.walk','glob'模塊等等。但是如果你致力於這種方法,你也可以做一些類似'command.getoutput('find'%s「-name」* .txt「'%os.getcwd())'。 '打印'那個字符串,我建議你傳遞給getoutput來看看它做了什麼。 – jedwards

+0

你是儀式,它在Python shell中工作。我在tcsh中運行這個程序。不知道這與它有什麼關係。 – Deep

回答

1

只是把它作爲替代。

假設你只需要在一個目錄下(即不遞歸)。我寧願嘗試使用glob搜索(與/假設行結束,否則將需要被添加到字符串):

import glob 
for line in files: 
    print(glob.glob(line+"*.txt")) 

如果遞歸(Python3.5>):

import glob 
for line in files: 
    print(glob.glob(line+"**/*.txt"),recursive=True) 
+0

也更好,因爲這是一個獨立於平臺的解決方案,與我的不同。 Mine只會在* Nix系統上運行,你的將在Windows上運行。 +1。 –