0

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

1 Answers1

0

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\'.") 
Pepsi-Joe
  • 447
  • 1
  • 10
  • Note that as it stands your code will do nothing to a file if the user doesn't enter a correct response as it will just move onto the next file. This may or may not be okay for what you are doing but it is something to consider. – Pepsi-Joe Jan 08 '22 at 06:38
  • can it be modified little bit if directory exist it shows error can this portion be done automatic –  Jan 08 '22 at 07:13
  • Sure. Instead of an error, I have added code that will just make the directory if it doesn't exist. I find this is better than just chucking an error. – Pepsi-Joe Jan 08 '22 at 07:30
  • i want to go back to see previous plot at this time its not working, can this be implemented in one line –  Jan 08 '22 at 12:24
  • Not easily. For loops can't do that. See https://stackoverflow.com/questions/14374181/moving-back-an-iteration-in-a-for-loop – Pepsi-Joe Jan 08 '22 at 23:05