gpt4 book ai didi

python - 如何通过循环 subprocess/popen 使用从文件读取的多个变量

转载 作者:行者123 更新时间:2023-11-30 23:47:33 24 4
gpt4 key购买 nike

我正在使用 python 从我的 Linux 操作系统读取 2 个文件。其中一个包含单个条目/数字“日期”:

20111125

另一个文件包含许多条目,“TIME”:

042844UTC044601UTC...044601UTC

我能够读取文件并分配给适当的变量。然后我想使用变量来创建文件夹路径、移动文件等...例如:

$PATH/20111125/042844UTC$PATH/20111125/044601UTC$PATH/20111125/044601UTC

等等。

不知何故,这不适用于一次传递的多个变量:

import subprocess, sys, os, os.path
DATEFILE = open('/Astronomy/Sorted/2-Scratch/MAPninox-DATE.txt', "r")
TIMEFILE = open('/Astronomy/Sorted/2-Scratch/MAPninox-TIME.txt', "r")
for DATE in DATEFILE:
print DATE,
for TIME in TIMEFILE:
os.popen('mkdir -p /Astronomy/' + DATE + '/' TIME) # this line works for DATE only
os.popen('mkdir -p /Astronomy/20111126/' + TIME) # this line works for TIME only
subprocess.call(['mkdir', '-p', '/Astronomy/', DATE]), #THIS LINE DOESN'T WORK

谢谢!

最佳答案

我建议使用os.makedirs(它的作用与mkdir -p相同)而不是subprocesspopen :

import sys
import os
DATEFILE = open(os.path.join(r'/Astronomy', 'Sorted', '2-Scratch', 'MAPninox-DATE.txt'), "r")
TIMEFILE = open(os.path.join(r'/Astronomy', 'Sorted', '2-Scratch', 'MAPninox-TIME.txt'), "r")

for DATE in DATEFILE:
    print DATE,

for TIME in TIMEFILE:
os.makedirs(os.path.join(r'/Astronomy', DATE, TIME))

astrDir = os.path.join(r'/Astronomy', '20111126', TIME)
try
os.makedirs(astrDir)
except os.error:
print "Dir %s already exists, moving on..." % astrDir
# etc...

然后使用 shutil对于任何 cp/mv/etc 操作。

<小时/>

来自os Docs :

os.makedirs(path[, mode])
Recursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory. Raises an error exception if the leaf directory already exists or cannot be created. The default mode is 0777 (octal). On some systems, mode is ignored. Where it is used, the current umask value is first masked out.

关于python - 如何通过循环 subprocess/popen 使用从文件读取的多个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8290980/

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