'How to get program to print out dir once, change the cd, and open a text file?
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?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
