12

I'm trying to write some text to a file, and here's what i tried :

text = "Lorem Ipsum is simply dummy text of the printing and typesetting " \
                  "industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s," \
                  " when an unknown printer took a galley of type and scrambled it to make a type specimen book."
target = open("file", 'wb')
target.writelines(text)

And I get an empty file. How can I do this?

Neuron
  • 5,141
  • 5
  • 38
  • 59
Ashref
  • 309
  • 1
  • 2
  • 12

4 Answers4

14

This is how to print to a txt file:

file = open("Exported.txt", "w")
file.write("Text to write to file")
file.close() #This close() is important

Another way to do so would to be:

with open('Exported.txt', 'w') as file:
   file.write("Text to write to file")

This is a program I made to write a txt file:

import os.path

def start():

    print("What do you want to do?")
    print("    Type a to write a file")
    print("    Type b to read a file")
    choice = input("            -")
    if choice == "a":
        create()
    elif choice == "b":
        read()
    else:
        print("Incorrect spelling of a or b\n\n")
        start()


def create():

    print()
    filename = input("What do you want the file to be called?\n")
    if os.path.isfile(filename):
        print("This file already exists")
        print("Are you sure you would like to overwrite?")
        overwrite = input("y or n")
        if overwrite == "y":
            print("File has been overwritten")
            write(filename)
        else:
            print("I will restart the program for you")
    elif not os.path.isfile(filename):
        print("The file has not yet been created")
        write(filename)
    else:
        print("Error")





def write(filename):
    print()
    print("What would you like the word to end writing to be?")
    keyword = input()
    print("What would you like in your file?")
    text = ""
    filename = open(filename, 'w')
    while text != keyword:
        filename.write(text)
        filename.write("\n")
        text = input()


def read():
    print()
    print("You are now in the reading area")
    filename = input("Please enter your file name:     -")
    if os.path.isfile(filename):
        filename = open(filename, 'r')
        print(filename.read())
    elif not os.path.isfile(filename):
        print("The file does not exist\n\n")
        start()
    else:
        print("Error")


start()
Rlz
  • 1,649
  • 2
  • 13
  • 36
  • @Ashref If my code has helped, please upvote and if it has answered your question, please mark this as the answer by pressing the green tick. Then other people with the same problem and can find this answer to help them with their problem too. Thanks! PS. I also made sure to upvote your question :) – Rlz Nov 07 '16 at 20:48
4

writelines expects an iterable (e.g. a list) of lines, so don't use that. And you need to close the file to save the changes, which is best done with a with statement:

with open("file", 'wb') as target:
    target.write(text)
Alex Hall
  • 34,833
  • 5
  • 57
  • 89
  • Yup, the problem was with the closing, also i changed writelines to write and it works fine. – Ashref Nov 07 '16 at 20:41
2

The code you've provided produces a file named file with the desired lines. Perhaps you meant to save it as "file.txt". Also, the 'b' in the 'wb' flag tells the code to write the file in binary mode (more information here). Try just using 'w' if you want the file to be readable.

Finally it is best practice to use the with statement when accessing files

text ="Lorem Ipsum is simply dummy text of the printing and typesetting " \
              "industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s," \
              " when an unknown printer took a galley of type and scrambled it to make a type specimen book."
with open("file.txt", 'w') as f:
    f.write(text)
Community
  • 1
  • 1
Mark Hannel
  • 767
  • 5
  • 12
2

By this way you should close the file directly:

target = open("filename.txt", 'w')
target.writelines(text)
target.close()

By this way the file closed after the indented block after the with has finished execution:

with open("filename.txt", "w") as fh:
    fh.write(text)

See here for more info.

Neuron
  • 5,141
  • 5
  • 38
  • 59
Benny
  • 2,233
  • 1
  • 22
  • 27