Python Forum
Thread Rating:
  • 1 Vote(s) - 1 Average
  • 1
  • 2
  • 3
  • 4
  • 5
writing to a file?
#1
Have been trying to learn how to write to a file in Python 3, but i can't seem to get it right. I have created a continents.txt file and a continents.py file both of which are stored in the same directory.

def Main():
    continents = ["African", "Antarctic", "Asian", "Australian", European", "North_American", "South_American"]

with open("continents.txt", 'w') as f:
    for continent in continents:
    f.write(continent + "\n")

if __name__ == "__main__":
    Main()
Could someone please tell this old fool where i am going wrong please.
Reply
#2
continents = ["African", "Antarctic", "Asian", "Australian","European", "North_American", "South_American"]
def Main():
    with open("continents.txt", 'w') as f:
        for continent in continents:
            f.write(continent + "\n")
 
if __name__ == "__main__":
    Main()
Reply
#3
lines 4-5-6 should be indented to the right to be part of Main() function. Then you need to fix their indentation too
Also you have missing open quotes for Europe
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
#4
I didn't run your code, but just from the code highlighting it is visible that you missed a first double quote (") in "European" (continents list).
Second and third problems are both indentation related. with open() block of code is not inside Main() function, which I believe is what you wanted to do. So now Main() function just assigns the list of continents to continents variable, and that's it.
Then the f.write is not part of the for loop, because it is not indented inside it. Thus f.write runs only once, and it doesn't know what continent is.
Reply
#5
Seems like i have been running around in circles for the last couple of days trying and failing to write text to a .txt file.
Perhaps i better start at the beginning so that everyone can see exactly what i've been doing and where i am going wrong.

I created an ordinary .txt file called emptyScriptFile.txt and saved it in the folder where i save all my .py script files.

I then created and saved a file called mainScript.py in the same folder as the emptyScriptFile.txt file which has the following contents:

#!/usr/bin/env python3
text = 'Some simple text to save\nThis is the Second line.'

myFile = open('emptyScriptFile.txt', 'w')
    myFile.write(text)
    myFile.close()
Could someone show me what i've done wrong please
Reply
#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


Possibly Related Threads…
Thread Author Replies Views Last Post
  Writing string to file results in one character per line RB76SFJPsJJDu3bMnwYM 4 1,387 Sep-27-2022, 01:38 PM
Last Post: buran
  Writing to json file ebolisa 1 1,012 Jul-17-2022, 04:51 PM
Last Post: deanhystad
  Writing to External File DaveG 9 2,502 Mar-30-2022, 06:25 AM
Last Post: bowlofred
  Writing to file ends incorrectly project_science 4 2,703 Jan-06-2021, 06:39 PM
Last Post: bowlofred
  Writing unit test results into a text file ateestructural 3 4,772 Nov-15-2020, 05:41 PM
Last Post: ateestructural
  Writing to file in a specific folder evapa8f 5 3,444 Nov-13-2020, 10:10 PM
Last Post: deanhystad
  Failure in writing binary text to file Gigux 7 3,825 Jul-04-2020, 08:41 AM
Last Post: Gigux
  writing data to a csv-file apollo 1 2,378 Jul-03-2020, 02:28 PM
Last Post: DeaD_EyE
  Writing to File Issue Flash_Stang 3 2,530 Jun-05-2020, 05:14 AM
Last Post: Gribouillis
  Help! Formatting and Writing to a File bwdu 2 2,418 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