【问题标题】:copy files based on choice of plot根据情节选择复制文件
【发布时间】:2022-01-08 06:21:36
【问题描述】:

我在一个目录中有许多 .txt 文件。起初我想在屏幕上一个一个地绘制文件,如果看起来不错,那么我想将 .txt 文件复制到一个名为“test_folder”的目录中。 如果它看起来不正常,那么我不想将 .txt 文件复制到“test_folder”目录。

我尝试了下面的脚本,但是我不能这样做,因为我是 python 新手。我希望专家可以帮助我克服这个问题。在此先感谢。

import numpy as np
import os,glob,shutil
import matplotlib.pyplot as plt

os.mkdir('test_folder')

for filex in glob.glob("*.txt"):
    print(filex)
    data=np.loadtxt(filex)
    plt.plot(data)
    plt.show()

    if plot_looks_nice == "yes": 
    #copy the filex to the directory "test_folder"
       shutil.copy(filex,'test_folder')
    elif plot_looks_nice == "no": 
    #donot copy the filex to the directory "test_folder"
         print("not copying files as no option chosen")
    else: 
    print("Please enter yes or no.") 

【问题讨论】:

    标签: python numpy for-loop matplotlib operating-system


    【解决方案1】:

    你很接近。您想使用input() 来提示用户并通过他们的输入返回一个变量。

    创建目录的最佳方法是使用 pathlib (python >= 3.5) 递归地创建不存在的目录。这样您就不必担心由于目录不存在而导致的错误

    查看下面的修改代码。

    import numpy as np
    import os,glob,shutil
    import matplotlib.pyplot as plt
    from pathlib import Path
    
    Path("test_folder").mkdir(exist_ok=True)
    
    for filex in glob.glob("*.txt"):
        print(filex)
        data=np.loadtxt(filex)
        plt.plot(data)
        plt.show()
    
        plot_looks_nice = input('Looks good? ')
    
        if plot_looks_nice == "y": #use single letters to make your work faster
        #copy the filex to the directory "test_folder"
           shutil.copy(filex,'test_folder')
        elif plot_looks_nice == "n": 
        #donot copy the filex to the directory "test_folder"
             print("not copying files as no option chosen")
        else: 
        print("Please enter \'y\' or \'n\'.") 
    

    【讨论】:

    • 请注意,如果用户没有输入正确的响应,您的代码将不会对文件执行任何操作,因为它只会移动到下一个文件。这可能适合您的工作,也可能不适合,但需要考虑。
    • 如果目录存在,可以稍微修改一下,显示错误这部分可以自动完成
    • 当然。我添加了代码,而不是错误,如果它不存在,它将只创建目录。我发现这比仅仅抛出一个错误要好。
    • 我现在想回去看以前的情节它不起作用,这可以在一行中实现
    • 不容易。 For 循环不能做到这一点。见stackoverflow.com/questions/14374181/…
    猜你喜欢
    • 2016-12-09
    • 1970-01-01
    • 2011-04-19
    • 1970-01-01
    • 1970-01-01
    • 2017-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多