如何使用循环中的子进程/popen从文件读取多个变量

2024-06-28 11:13:27 发布

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

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

20111125

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

042844UTC
044601UTC
...
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

谢谢!在


Tags: 文件pathfordatetimeos条目open
2条回答

我在你的代码中看到几个错误。在

os.popen('mkdir -p /Astronomy/' + DATE + '/' TIME) # this line works for DATE only

这是一个语法错误。我想你是想拥有'/' + TIME,而不是{}。我不明白你说的“这条线只适用于约会”是什么意思?在

^{pr2}$

你想叫什么命令?我从其余代码中猜出您正在尝试执行mkdir -p /Astronomy/<<DATE>>。但这不是你所编码的。传递给subprocess.call的列表中的每一项都是一个单独的参数,因此您编写的内容将显示为mkdir -p /Astronomy <<DATE>>。这将尝试创建两个目录,一个是根目录/Astronomy,另一个是当前工作目录中名为DATE的目录。在

如果我对你想做的事情是正确的,那么正确的一行应该是:

subprocess.call(['mkdir', '-p', '/Astronomy/' + DATE])

在我看来,chown的答案是使用os.makedirs(并使用os.path.join拼接路径,而不是字符串+)是一种更好的通用方法。但据我所知,这就是你当前的代码不能正常工作的原因。在

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

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...

然后将^{}用于任何cp/mv/etc操作。在


^{} 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.

相关问题 更多 >