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

2024-04-23 18:34:34 发布

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

我正在创建一个文件名列表。你知道吗

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)

Tags: 文件pathinself列表forositem
1条回答
网友
1楼 · 发布于 2024-04-23 18:34:34

您对pythonfor如何工作的理解有点欠缺。你知道吗

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

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

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文件列表时也犯了同样的错误。你知道吗

相关问题 更多 >