Hello, I am very new to Python but as I am currently studying Network engineering and Cyber security I am required to learn it, I am currently working on a socket server and client program that has the ability to download and edit files mainly .txt, I have managed to get that part of the program working but wish to add the ability to create the file if it does not exists, the problem I am facing is that when I run the program it asks me if I wish to create the file and notifies me that it has done so but when I check it has not.
I would be most appreciative if someone could take a look and help me as I only have 9 days left until I have to submit this.
Thank you, that worked the only issue left for me is that when I add information to it to the newly created file (Which is the next step) it dose not save to the text.txt it is just blank.
apparently line 35,
(f = open(myFile, ‘r’) # Opens the file for [r]ead only) is unreachable?
sure thing, I have fixed the issue with it writing to an existing file so the only issue is writing to a newly created file. It says it has but it doesn’t and then closed abruptly.
import os # Imports the OS module
def main(): # Main function
answer = input("Do you want to edit a file? y/n\n>").lower()
if "y" == answer:
myFile = input("Please enter the name of the file you wish to edit.. ")
if os.path.exists('./' + myFile): # True control flow statement
overWrite = input("That file already exists - Overwrite? y/n ").lower()
if "y" in overWrite:
pass
else:
print("sorry that file does not exist")
answer = input("Do you want to create the file? y/n\n>").lower()
if "y" in answer:
if not os.path.exists('./' + myFile):
with open('./' + myFile, "x"):
pass
else:
print("Goodbye")
return
changeNum = int(input("Please enter the line number you wish to change "))
newLine = input("Please enter the new text.. ")
print("The file has been edited")
print("Goodbye")
f = open(myFile, 'r')
content = f.readlines()
f.close()
f = open(myFile, 'w')
content[changeNum - 1] = newLine + "\n"
f.writelines(content)
for things in content:
print(things)
f.close()
if "__name__ == __main_":
main()
I can edit an existing file, I can create a new file when asked, the issues I’m having are when asked if I want to edit a line of text it goes through the right steps but then closes abruptly then upon checking the newly created.txt file it is empty.
been stuck trying to fix this for days now.