【问题标题】:Python: How can i concatenate list of pathPython:如何连接路径列表
【发布时间】:2015-04-09 20:35:58
【问题描述】:

我正在运行一个子进程,它为我提供了子目录的路径列表。现在对于列表中的每个成员(路径),我试图连接以获得最终路径。但由于列表成员和字符串属于不同的数据类型,我无法连接列表中的路径和另一个字符串以生成最终路径。

有人可以帮我解决这个问题吗?

directories = subprocess.check_output(
    ['find', '/Users/sdb99/Desktop', '-type', 'd', '-mmin', '-60', '-type', 'd','-mmin', '+5']).splitlines()
number_of_directories = len(directories)
n = 1
for n in range(0,number_of_directories):                
  dire =str(directories[n]).strip('[]')
  b_new = dire[n] + '/1'
  print(b_new)

【问题讨论】:

  • 您的代码非常混乱。你遇到了什么错误?您能否举例说明您的 subprocess 调用的返回值可能是什么以及您想将其转换成什么?另外,您使用的是哪个版本的 Python(您已使用 Python 2.7 和 Python 3.x 标记了您的问题,这两个主要变体,但它们之间存在显着差异)。
  • 澄清一下:directories = subprocess.check_output( ['find', '/Users/sdb99/Desktop', '-type', 'd', '-mmin', '-60' , '-type', 'd','-mmin', '+5']).splitlines() 这行给了我在桌面文件夹上创建的目录路径。在列表中的每个路径之后,我想添加其他字符串,例如:'Users/sdb99/Desktop/UntitledFolder2'(this i gt from list) + /old_files。这应该生成像这样的完整路径:'Users/sdb99/Desktop/UntitledFolder2/old_files.我无法创建这两条路径属于不同的数据类型。

标签: python python-2.7 python-3.x path


【解决方案1】:

没有必要剥离任何东西,你的逻辑很接近但有缺陷。该列表由字符串组成,您只需将它们分配给循环中的字符串即可。

dire = ''
directories = subprocess.check_output(
    ['find', '/Users/sdb99/Desktop', '-type', 'd', '-mmin', '-60', '-type', 'd','-mmin', '+5']).splitlines()
number_of_directories = len(directories)
for n in range(0,number_of_directories):
  dire += directories[n]
  dire += ' ' 
print dire
type dire

【讨论】:

  • 感谢 castaway2000 的回复。但我收到以下错误:回溯(最近一次通话最后一次):文件“/Users/sdb99/PycharmProjects/Scan_log_version1.1/test_pathselection.py”,第 10 行,在 可怕 += 目录 [n] TypeError:可以't 将'bytes' 对象隐式转换为 str 进程以退出代码 1 结束
  • 我不能 100% 确定这是否可行,但试试这个:dire += str(directories[n])
  • 或者也试试这个可怕的 += 目录 [n].decode("utf-8") 但调试女巫索引可能是明智的做法导致了这个问题。打印 n 并在发生错误后查看输出,然后您可以添加条件语句来解码该索引(如果需要)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多