I am writing a program to take input from a user and print out the contents of the cwd, to be able to change the cwd you're working in, to open a text file in the cwd, or to quit the program.
So far, I can get the dir command to list the .txt files in the cwd but its on an endless loop. I can specify a new directory, but the question just repeats itself, and I can get the program to respond to the quit command.
Here is my code:
import os cwd = os.getcwd() print("Current working directory: ", cwd) dirlist = input("Choose DIR, CD, OPEN, or QUIT: ") while True: if dirlist == "dir": for x in os.listdir(): if x.endswith(".txt"): print(x) elif dirlist == "cd": for x in os.listdir(): changedir = input("Change to what path?") print(cwd) elif dirlist == "open": for x in os.listdir(): opendir = input("Open what file?") open(opendir) else: print("Ok, goodbye.") break What do I need to do to accomplish these three things:
- not have an endless loop with the dir input and just loop back to the initial question.
- take input for a new directory and loop back to the initial question while staying in the new directory.
- open a text editor after the open input.
Thanks for any advice.
Edit:
Thanks to people in the comments I have solved questions 1 and 3, but question 2 is still stumping me. Here is my current code-
elif dirlist == "cd": for x in os.listdir(): changedir = input("Change to what path?") os.chdir(cwd) print (changedir) break How do I get the cwd to show up and print as what it was renamed with the input from changedir?
whileloop should include those first three lines of code (after theimport), don't you think? And, by the way, you are not actually changing directories, nor are you opening an editor.openjust opens a handle to the file, and since you don't save it, it will immediately close.continuewhich restarts the loop from the top. Also for 3 like the above comment mentions, to open that file you will actually need to do something that can run on the command line, see the answer here: stackoverflow.com/questions/6178154/…