正在创建要写入文件的列表错误列表索引超出范围



我正在创建一个文件名列表。

self.hostTestFiles = ["hostTest1_ms.dat","hostTest2_ms.dat","hostTest3_ms.dat","hostTest4_ms.dat",
                          "hostTest5_ms.dat", "hostTest6_ms.dat","hostTest7_ms.dat","hostTest8_ms.dat",
                          "hostTest9_ms.dat","hostTest10_ms.dat"]

然后为文件的路径创建另一个列表。

self.hostFilePaths = []
for i in self.hostFilePaths:
        os.path.join(self.hostFolder, self.hostTestFiles[i])

我有一个函数,可以将随机数据写入每个文件,但它说列表索引超出了的范围

def createFile (self):
    print "creating file"
    for item in self.hostFilePaths:
        with open(item, 'wb') as fout:
            fout.write(os.urandom(10567))
            fout.flush()
            os.fsync(fout.fileno())

然后我想把这些文件从我的电脑复制到usb上,然后在usb上重命名,但这似乎也不起作用。有人能告诉我哪里出了问题吗?

 self.usbFilePaths = []
 self.newUsbFilePaths = []

 for i in self.usbFilePaths:
        os.path.join(self.usbFolder, self.hostTestFiles[i])
 for i in self.newUsbFilePaths:
        os.path.join(self.usbFolder, self.usbTestFiles[i])

 def copyToUsb (self):
    print "Copying file from comp to usb"
    for item in self.hostFilePaths:
        shutil.copy(item, self.usbFolder)
        time.sleep(4)
    for i in range(0,10):
        print "here 2"
        shutil.move(self.usbFilePaths[i], self.newUsbFilePaths[i])
        time.sleep(4)

您对python for如何工作的理解有点欠缺。

for i in self.hostFilePaths:
    os.path.join(self.hostFolder, self.hostTestFiles[i])

不使用os.path.join操作的结果填充self.hostFilePaths,它保持为空并导致索引超出范围错误。它应该读取

for i in self.hostTestFiles:
    self.hostFilePaths.append(os.path.join(self.hostFolder, i))

或者,更像蟒蛇,你可以通过列表理解来做到这一点。

self.hostFilePaths = [ os.path.join(self.hostFolder, i) for i in self.hostTestFiles ]

你在创建usb文件列表时也犯了同样的错误。

最新更新