创建文件后,如何创建文件并对文件执行操作?

时间:2019-06-24 13:38:18

标签: python python-3.x

我正在使用python 3.6生成文件。然后,我需要通过自动邮件发送这些文件。 这是一些代码:

myFiles = []
myFiles.append(getFirstFile()) # creates a file and returns its path
                               # its name is '2019-06-24_15-01-57_hist'
myFiles.append(getSecondFile()) # creates another file and returns its path

# myFiles is a list of strings
sendAutoMail(myFiles) # sends an automatic mail with the files attached

如果未在同一脚本中实现,则所有这些功能都可以正常工作。但是现在我将所有这些放在一起,这就是我从sendAutoMail()函数得到的错误:

FileNotFoundError: [Errno 2] No such file or directory: '2019-06-24_15-01-57_hist'

当我查看目录时,确实创建了文件。

使用getFirstFile()getSecondFile()创建文件,然后以两个步骤运行sendAutoMail([File1, File2]) 似乎正常。但是,它不能用于唯一的脚本。

有什么想法吗?

编辑:好的,这里有功能,不确定是否会有所帮助

def getFirstFile(mean, variance): # prend en paramètres une moyenne et une variance
    import matplotlib.pyplot as plt
    import numpy as np
    import scipy.stats as stats
    import math

    mu = mean
    sigma = math.sqrt(variance)
    x = np.linspace(mu - 3*sigma, mu + 3*sigma, 100)
    plt.grid(True)
    plt.plot(x, stats.norm.pdf(x, mu, sigma)) #création d'une courbe normale centrée en mu et d'écart type sigma
    # plt.show()
    filename = dateFileName()+"_firstFunction"
    plt.savefig(filename)

def dateFileName():
    import datetime
    ladate = str(datetime.datetime.now()) # récupération de la date et formattage
    ladate = ladate.split(sep=".")
    ladate = ladate[0].replace(" ","_")
    ladate = ladate.replace(":","-")
    return ladate

我将日期用作文件名,因为我不知道任何其他选择来确保文件名是唯一的。

1 个答案:

答案 0 :(得分:0)

深入研究matplotlib的源代码,我发现使用路径(仅名称是相对路径)调用plt.savefig(filename)会随后调用函数Figure.print_[format](filename, ...),其格式为save格式,例如PDF,PNG,TIFF...。默认值为PNG。

Figure.print_png使用枕头来写图像,特别是Pillow.Image.save。该函数将打开文件,写入文件并关闭文件。

问题是,它直接关闭文件 ,仅此而已。直接关闭文件时,python使用默认的系统缓冲区和刷新周期,因此当直接关闭文件时,不会立即将其写入磁盘,或者至少不会完全写入磁盘(取决于部分文件的大小可能已保存) )。

为防止这种情况发生,请在with语句中打开代码中的文件,该语句在退出时会刷新并关闭文件,如下所示:

def getFirstFile(mean, variance): # prend en paramètres une moyenne et une variance
    import matplotlib.pyplot as plt
    import numpy as np
    import scipy.stats as stats
    import math

    mu = mean
    sigma = math.sqrt(variance)
    x = np.linspace(mu - 3*sigma, mu + 3*sigma, 100)
    plt.grid(True)
    plt.plot(x, stats.norm.pdf(x, mu, sigma)) #création d'une courbe normale centrée en mu et d'écart type sigma
    # plt.show()
    filename = dateFileName()+"_firstFunction"
    with open(filename, 'r+b') as fl:
        plt.savefig(fl)
    return filename

应该应该解决您的问题,在某些情况下,最后一个缓冲部分可能仍未保存。在这种情况下,您可以在return filename语句之前使用os.fsync(fl)强制将缓冲区写入磁盘。