如何将完整文件路径拆分为路径和没有扩展名的文件名

2024-05-26 21:51:48 发布

您现在位置:Python中文网/ 问答频道 /正文

如何将完整的文件路径拆分为路径和没有扩展名的文件名? 我正在查找扩展名为.conf: find/path-name.conf /path/file1.conf /路径/smth/file2.conf /路径/smth/file3.conf /路径/smth/smth1/.conf ... /路径/smt//*.conf

我需要字符串形式的输出(不带扩展名.conf): /路径;文件1 |路径/smth;文件2;文件3 |

最好的方法是什么? 我在考虑一个解决方案——将查找工作的输出保存到一个文件中,并在循环中处理它们……但也许有一种更有效的方法。 对不起,我是新手。。 谢谢你们的反馈,伙计们


Tags: 文件path方法字符串name路径文件名conf
3条回答

既然你提到了.conf,这有帮助吗

kent$ basename -s .conf '/path/smth/file2.conf'
file2

kent$ dirname '/path/smth/file2.conf'          
/path/smth

要在Bash中执行此操作,请执行以下操作:

find /path/ -type f -name "*.conf"

请注意,如果要在Bash脚本中执行此操作,可以将/path/存储在一个变量中,例如一个命名目录,并按如下方式更改命令:

find $directory -type f -name "*.conf"

要在Python中执行此操作,请执行以下操作:

import os
PATH = /path/

test_files = [os.path.join(dp, f) for dp, dn, filenames in os.walk(PATH) for f in filenames
              if os.path.splitext(f)[1] == '.json']

在Python列出的here中也有其他一些方法可以实现这一点

^{} parameter parsing简单、快速、轻量级

for fp in /path/file1.conf /path/smth/file2.conf /path/smth/file3.conf; do
  p="${fp%/*}"   # %  strips the pattern from the end       (minimal,   non-greedy)
  f="${fp##*/}"  # ## strips the pattern from the beginning (max-match, greedy)
  f="${f%.*}"    # end-strip the already path-cleaned filename to remove extention
  echo "$p, $f"
done
/path, file1
/path/smth, file2
/path/smth, file3

要获得您显然想要的格式,请执行以下操作-

declare -A paths                     # associative array
while read -r fp; do
  p=${fp%/*} f=${fp##*/};            # preparse path and filename
  paths[$p]="${paths[$p]};${f%.*}";  # p as key, stacked/delimited val 
done < file

然后堆叠/分隔数据集

for p in "${!paths[@]}"; do printf "%s|" "$p${paths[$p]}"; done; echo
/path;file1|/path/smth;file2;file3|

对于每个键,打印键/val和分隔符^换行符结尾处的{}

如果不需要拖曳管道,请将其全部指定给第二个循环中的一个变量,而不是将其打印出来,并在末端修剪拖曳管道

$: for p in "${!paths[@]}"; do out="$out$p${paths[$p]}|"; done; echo "${out%|}"
/path;file1|/path/smth;file2;file3

有些人会告诉你不要用bash来处理这么复杂的事情。请注意,这可能会导致糟糕的维护,尤其是如果您身后的维护人员不是专家,也懒得去做RTFM

如果您在示例中确实需要嵌入的空间,那么您的规则是不一致的,您必须解释它们

相关问题 更多 >

    热门问题