python os.mkdir(os.path.join($folder1,$folder2))在使用shell Package 器运行时在$folder2之前添加“\”

bf1o4zei  于 2023-06-28  发布在  Python
关注(0)|答案(2)|浏览(107)

我为一个python脚本编写了一个shell/SGE Package 器,用于图像分析研究。我的python脚本的第一步是创建文件夹,以复制每个主题的python脚本SC_qc.py的输出(如下所示):

# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""

import numpy
import matplotlib.pyplot as plt
import nibabel as nib
import sys
import os

# Get subject IDs and put them in list
txtfile = sys.argv[1]
subjects = [ s.strip() for s in open(txtfile, 'r').readlines() ]

comp_space = "\\\\share\\org\\comp_space\\doej\\SC_QC\\"
sc_space = "\\\\share\\org\\projects\\autism\\Protocols\\StructuralConnectivity\\"

for folder in subjects:
    try:
        os.mkdir(os.path.join(comp_space,folder))
    except FileExistsError:
        pass

问题是,似乎在主题ID之前添加了一个“/”,该主题ID存储为folder,来自subjects变量(通过循环/迭代主题ID subjects的文本文件获得)。

Executing on: 2118ffn001
Executing in: /share/org/projects/autism/
Executing at: Tue Jun 27 16:46:04 EDT 2023
Traceback (most recent call last):
  File "/share/comp_space/doej/SC_qc.py", line 25, in <module>
    os.mkdir(os.path.join(comp_space,folder))
FileNotFoundError: [Errno 2] No such file or directory: '\\\\share\\org\\comp_space\\doej\\SC_QC\\/subject_01'

文件夹\\\\\share\\org\\comp_space\\doej\\SC_QC\\本身存在,我确实尝试使用dos2unix无济于事(得到了同样的错误)。
有没有可能我应该使用sed从我的文本文件中删除一个隐藏的字符,这个隐藏的字符可能是什么?还是我把subjects读成subjects = [ s.strip() for s in open(txtfile, 'r').readlines() ]中的变量有什么问题?我的txtfile变量只是我所有的主题ID,在文本文件中每行列出一个。
先谢谢你了!

vsaztqbk

vsaztqbk1#

Pathlib是你简化事情的朋友。

import numpy
import matplotlib.pyplot as plt
import nibabel as nib
import sys
from pathlib import Path

# Get subject IDs and put them in list
txtfile = sys.argv[1]
# It's much safer to use `with` when opening files.
with open(txtfile, 'r') as f:
    subjects = f.read().splitlines()

# Assuming you're using windows, these should turn out as expected. I tested them with `PureWindowsPath`
comp_space = Path("\\\\share\\org\\comp_space\\doej\\SC_QC\\")
sc_space = Path("\\\\share\\org\\projects\\autism\\Protocols\\StructuralConnectivity\\")

for folder in subjects:
    # Make the directory and all necessary parent directories, (parents=True) 
    # If it already exists, don't raise an error. (exists_ok=True)
    comp_space.joinpath(folder).mkdir(parents=True, exists_ok=True)
4jb9z9bj

4jb9z9bj2#

而不是带反斜杠的路径

\\\\share\\org\\comp_space\\doej\\SC_QC\\

使用常规的/ s -并且不要有结尾的目录分隔符。尾随的\\可能会扰乱os.path.join的路径构建。相反,让它:

//share/org/comp_space/doej/SC_QC

输出中的这一行让我怀疑share是否真的是Windows共享:

Executing in: /share/org/projects/autism/

如果不是,而是一个挂载的(NFS或类似的)文件系统,则从路径的开头删除一个/,这将使其

/share/org/comp_space/doej/SC_QC

然而,另一个输出提到

/share/comp_space/doej/

这意味着/org应该被删除,使其

/share/comp_space/doej/SC_QC

相关问题