Python Forum
Thread Rating:
  • 1 Vote(s) - 1 Average
  • 1
  • 2
  • 3
  • 4
  • 5
writing to a file?
#6
in this case lines 5-6 should not be indented. You will get indentation error from this code. But it's better to use with context manager when open the file, like you did before. So, this code should be

text = 'Some simple text to save\nThis is the Second line.'
 
myFile = open('emptyScriptFile.txt', 'w')
myFile.write(text)
myFile.close()
but better

text = 'Some simple text to save\nThis is the Second line.'

with open('emptyScriptFile.txt', 'w') as my_file:
    my_file.write(text)
note that with both snippets the file will be saved in the current working directory, i.e. the one from which you execute the script.
Quote:I created an ordinary .txt file called emptyScriptFile.txt and saved it in the folder where i save all my .py script files.
Also, if you want to append at the end of already existing file, you should open the file in 'a' i.e. append mode, not 'w'
also, my_file.write() will not add new line at the end of your text.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Messages In This Thread
writing to a file? - by oldDog - Aug-19-2018, 11:31 AM
RE: writing to a file? - by Axel_Erfurt - Aug-19-2018, 11:43 AM
RE: writing to a file? - by buran - Aug-19-2018, 11:45 AM
RE: writing to a file? - by j.crater - Aug-19-2018, 11:48 AM
RE: writing to a file? - by oldDog - Aug-23-2018, 01:03 PM
RE: writing to a file? - by buran - Aug-23-2018, 01:48 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Writing string to file results in one character per line RB76SFJPsJJDu3bMnwYM 4 1,604 Sep-27-2022, 01:38 PM
Last Post: buran
  Writing to json file ebolisa 1 1,112 Jul-17-2022, 04:51 PM
Last Post: deanhystad
  Writing to External File DaveG 9 2,803 Mar-30-2022, 06:25 AM
Last Post: bowlofred
  Writing to file ends incorrectly project_science 4 2,924 Jan-06-2021, 06:39 PM
Last Post: bowlofred
  Writing unit test results into a text file ateestructural 3 5,010 Nov-15-2020, 05:41 PM
Last Post: ateestructural
  Writing to file in a specific folder evapa8f 5 3,665 Nov-13-2020, 10:10 PM
Last Post: deanhystad
  Failure in writing binary text to file Gigux 7 4,050 Jul-04-2020, 08:41 AM
Last Post: Gigux
  writing data to a csv-file apollo 1 2,502 Jul-03-2020, 02:28 PM
Last Post: DeaD_EyE
  Writing to File Issue Flash_Stang 3 2,727 Jun-05-2020, 05:14 AM
Last Post: Gribouillis
  Help! Formatting and Writing to a File bwdu 2 2,525 Apr-19-2020, 09:29 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020