我在一個目錄中有許多 .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.")
uj5u.com熱心網友回復:
你很接近。你想用它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\'.")
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/406719.html
標籤:
