作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下代码。它适用于第一个目录,但不适用于第二个目录......我想做的是计算不同目录中每个文件的行数。
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/
我是一名优秀的程序员,十分优秀!