2016-10-06 66 views
0

我有以下代碼。它適用於第一個目錄,但不適用於第二個目錄... 我想要做的是計算不同目錄中每個文件的行數。如何在Python中更改目錄?

import csv 
import copy 
import os 
import sys 
import glob 

os.chdir('Deployment/Work/test1/src') 
names={} 
for fn in glob.glob('*.c'): 
    with open(fn) as f: 
     names[fn]=sum(1 for line in f if line.strip() and not line.startswith('/') and not line.startswith('#') and not line.startswith('/*')and not line.startswith(' *'))  

print ("Lines test 1 ", names) 
test1 = names 

os.chdir('Deployment/Work/test2/src') 
names={} 
for fn in glob.glob('*.c'): 
    with open(fn) as f: 
     names[fn]=sum(1 for line in f if line.strip() and not line.startswith('/') and not line.startswith('#') and not line.startswith('/*')and not line.startswith(' *'))  

print ("Lines test 2 ", names) 
test2 = names 

print ("Lines ", test1 + test2) 

回溯:

FileNotFoundError: [WinError 3] The system cannot find the path specified: 'Deployment/Work/test2/src' 

回答

2

您必須根據需要返回到根目錄..,存儲根目錄或指定從您的家庭是完整的目錄:

curr_path = os.getcwd() 
os.chdir('Deployment/Work/test2/src') 

os.chdir(curr_path) 
os.chdir('Deployment/Work/test2/src') 

或者:

os.chdir('Deployment/Work/test2/src') 

os.chdir('../../../../Deployment/Work/test2/src') # Not advisable 

代替上述的,你可以考慮更多點Python的的方式來動態更改目錄,就像使用上下文管理的目錄:

import contextlib 
import os 

@contextlib.contextmanager 
def working_directory(path): 
    prev_cwd = os.getcwd() 
    os.chdir(path) 
    yield 
    os.chdir(prev_cwd) 

with working_directory('Deployment/Work/test1/src'): 
    names = {} 
    for fn in glob.glob('*.c'): 

with working_directory('Deployment/Work/test2/src'): 
    names = {} 
    for fn in glob.glob('*.c'): 
     ... 

只需指定從當前目錄的相對目錄,然後在該目錄中的上下文中運行代碼。

2

os.chdir被解釋爲相對於當前工作目錄。您的第一個os.chdir將更改工作目錄。系統嘗試查找相對於第一個路徑的第二個路徑。

有幾種方法可以解決這個問題。您可以跟蹤當前目錄並將其更改回來。否則,相對於第一個目錄製作第二個os.chdir。 (例如os.chdir(../../test2/src'),這有點醜陋,第三個選項是讓所有路徑都是絕對的,而不是相對的。

0

我想腳本不能正常工作,因爲您正在嘗試使用相對路徑更改目錄。這意味着當您執行第一個os.chdir時,您將工作目錄從當前的工作目錄更改爲'Deployment/Work/test1/src',並且當您第二次調用os.chdir時,該功能會嘗試將工作目錄更改爲'Deployment/Work/test1/src/Deployment/Work/test2/src',我認爲這不是您想要的。

爲了解決這個問題,你可以使用絕對路徑:

os.chdir('/Deployment/Work/test1/src')

或第一os.chdir之前,你可以跟蹤你的當前文件夾中:

current = os.getcwd() os.chdir('Deployment/Work/test1/src') ... os.chdir(current) os.chdir('Deployment/Work/test2/src')