Python:将指定大小的文件创建到指定位置,并记录它所花费的时间

时间:2013-09-16 16:01:30

标签: python python-3.x

出于测试目的,我想创建一个小实用程序,它会提示我想要创建的文件的大小以及我想要发送到的位置,然后记录创建文件所需的时间,在将结果记录在Excel电子表格之前。到目前为止,我有这个:

import time
import pythoncom
from win32com.client import Dispatch

#create file
myPath = input('Where do you want to write the file?')
size_MB = int(input('What sized file do you want to test with? (MB)'))
size_B = size_MB * 1024 * 1024
fName = '\pydatafile'
#start timer
start = time.clock()
f = open(myPath + fName,'w')
f.write("\x00" * size_B)
f.close()

#how much time it took
elapsed = (time.clock() -start)
print ("It took", elapsed, "seconds to write the", size_B, "MB file")
#I'll sort something out to work out Mbps when the rest is ready

#record results on Excel
xl = Dispatch('Excel.Application')
xl.visible= 0
wb = xl.Workbooks.Add(r'C:\Users\ryansinfield\Desktop\Book1.xlsm')
ws = wb.Worksheets(1)

#loop until empty cell is found in column
col = 1
row = 1
empty = False

while not empty:
    val = ws.Cells(row,col).value
    print("Looking for next available cell to write to...")
    if val == None:
        print("Writing result to cell")
        ws.Cells(row,col).value = Mbps
        empty = True
    row += 1

xl.Run('Save')
xl.Quit()

pythoncom.CoUninitialize()

这会将文件创建到指定位置ok,但文件创建是即时的。我为文件指定的大小无关紧要,它总是显示为0字节并创建微秒。

有什么方法可以创建一个实际文件,这样我可以更有效地测试局域网速度吗?

编辑:现在似乎在速度方面有效。我不知道为什么会这样,也许我是个笨蛋。但是我想添加一些内容。测试运行后是否可以删除空白文件?

1 个答案:

答案 0 :(得分:0)

您可能会感兴趣的一些事情:

  • 内置的os module有一些很好的函数来处理文件系统:

    • 使用os.path模块时,您不必担心在处理路径时依赖于平台的语法或反斜杠。

    • 您可以使用os.remove删除文件。

  • 因为你正在使用Excel,我猜你是在Windows上:在写入文件时考虑使用'wb'而不是'w'因为Windows deals with EOL characters differently than Unix.

  • "0.Df"%number可用于格式化带D位小数位的浮点数。

添加了以下更改的代码:

import os
import time
import pythoncom
from win32com.client import Dispatch

#create file
myDir = input('Where do you want to write the file?')
myPath = os.path.join(myDir, 'pydatafile')

size_MB = int(input('What sized file do you want to test with? (MB): '))
size_B = size_MB * 1024 * 1024

# create string to write
to_write = "\x00" * size_B

#start timer
start = time.clock()
f = open(myPath, 'wb')
f.write(to_write)
f.close()

#how much time it took
elapsed = time.clock() - start
print "It took %0.3f"%elapsed, "seconds to write the", size_MB, "MB file at a rate of %0.3f"%(size_MB/elapsed), "Mbps."

#record results on Excel
xl = Dispatch('Excel.Application')
xl.visible= 0
wb = xl.Workbooks.Add(r'C:\Users\ryansinfield\Desktop\Book1.xlsm')
ws = wb.Worksheets(1)

#loop until empty cell is found in column
col = 1
row = 1
empty = False

while not empty:
    val = ws.Cells(row,col).value
    print("Looking for next available cell to write to...")
    if val == None:
        print("Writing result to cell")
        ws.Cells(row,col).value = Mbps
        empty = True
    row += 1

xl.Run('Save')
xl.Quit()

pythoncom.CoUninitialize()

# Remove the file at the end
os.remove(myPath)