Home > Net >  copy files based on choice of plot
copy files based on choice of plot

Time:01-08

i have many .txt files in a directory.At first i want to plot the files one by one on the screen and if it looks fine then i want to copy the .txt file to a directory called "test_folder". If it doesnot looks fine then i donot want to copy the .txt file to the "test_folder" directory.

I tried the below script, however i couldn't do that as i am new to python. I hope experts may help me overcoming this problem.Thanks in advance.

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.") 

CodePudding user response:

You are pretty close. You want to use input() to prompt the user and get a variable back with their input.

The best way to make a directory is to use pathlib (python >= 3.5) to recursively create directories if they don't exist. This way you never have to worry about errors due to directories not existing

See modified code below.

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\'.") 
  •  Tags:  
  • Related