-2

Completely new and learning python, so please be patient with my noob problems lol. i tried entering this code:

file = open('Test.txt','w')
file.write('Hello world')

After that it doesn't give me an error but also wont open nor write. The Text.txt file is on my desktop and i tried direct path but also same problem. could i be missing something? Thank you in advance.

MrHotShot
  • 19
  • 6

2 Answers2

3

your file is not where you think it is try changing to this

print(os.getcwd())
file = open('Test.txt','w')
file.write('Hello world')
print("Wrote : {0}".format(os.path.abspath("Test.txt")))
print("Contents: ",open("Test.txt","r").read())

as an aside when opening for writing you should really use a filecontext

with open("Test.txt","w") as f:
     f.write('Hello world')

this ensures the file is properly closed afterwards

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
  • I tried this and it gives me the same issue. It goes off and no error message, but when i actually open the note it appears empty, which seems to be quite unusual from my research. – MrHotShot Mar 18 '20 at 03:30
  • see the first line ... the file you are opening is not the right file ... this should print the path to the right file in the above code – Joran Beasley Mar 18 '20 at 05:49
  • Yes I found my mistake you were right! Thank you so much! – MrHotShot Mar 19 '20 at 03:49
-1

my observations are as under. 1. After the second line of code , Python returns the no. of characters written into the file, in your case 11. Have you observed it?. 2. Although you may see your file using file explorer on your desktop, you won't see any thing written in it if you open it using notepad. For you to see the contents you wrote, you need to close the file by file.close() in python. 3. The file name is test.txt as you mentioned, but you have stated 'Text.txt' is on desktop. Pl. reconcile. best regards NR

Raghuraman
  • 81
  • 3