Home > Software design >  I need to be able to create a new file to a specific directory and then write to it. when running it
I need to be able to create a new file to a specific directory and then write to it. when running it

Time:01-02

I need to create a program that will use the OS library in order to validate that a directory exists before creating a file in that directory. The program will then prompt the user for the directory they would like to save the file in as well as the name of the file. The program should then prompt the user for their name, address, and phone number. The program will then write this data to a comma-separated line in a file and store the file in the directory specified by the user. Once the data has been written the program should read the file you just wrote to the file system and display the file contents to the user for validation purposes.

please help me because any work I'm doing is not working out.

this is what I did so far:

import os

print ("Hi, I can save a new file with your name, address, and phone number, in a specified directory for you.")
userPath = input("Give me the path to the directory that you want to save the new file in: \n")
try:
    os.path.isdir(userPath)
    
except:
    print("Specified directory path does not exist.")
    quit()
newFile = input("What do you want to name the new file?\n")
filePath = os.path.join(userPath, newFile)
name = input("What's your name?\n")
address = input("What's your address?\n")
number = input("What's your phone number?\n")
try:    
    with open(filePath, 'w') as file_object: #create new file
        data = (name   ", "   address   ", "   number)
        file_object.write(data) #write to file
except:
    print("Error creating/writing to new file.")
    quit()
try:
    with open(filePath) as file_object:
        print("Today we created a new file, "   newFile   ", and we added the following information to the file: ")
        print(file_object.read())
except:
    print("Error reading file.")
    quit()

CodePudding user response:

Just change this:

try:
    os.path.isdir(userPath)
    
except:
    print("Specified directory path does not exist.")
    quit()

To this:

if not os.path.isdir(userPath):
    print("Specified directory path does not exist.")
    quit()

CodePudding user response:

tried out on my machine (Ubuntu 20.04) and it worked perfectly: Result

I think that maybe your problem is that you need to add a full path to the program, what I mean by that is that when running the program you should not add something like:

Downloads

It should be like:

/home/<your-user>/Downloads

If you are on Windows you should use somehting like:

C:\Downloads

It depends on your OS, I hope that was helpful

  • Related