根据打印选择复制文件



我在一个目录中有许多.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.") 

您非常接近。您希望使用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'.") 

最新更新