gpt4 book ai didi

python - 如何在 Python 中更改目录?

转载 作者:行者123 更新时间:2023-12-02 17:24:26 24 4
gpt4 key购买 nike

我有以下代码。它适用于第一个目录,但不适用于第二个目录......我想做的是计算不同目录中每个文件的行数。

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'

最佳答案

您必须根据需要使用尽可能多的 .. 返回到根目录,存储根目录或从您的主目录指定一个完整目录:

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'):
...

您只需指定当前目录的相对目录,然后在该目录的上下文中运行您的代码。

关于python - 如何在 Python 中更改目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39900734/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com