Python:将文本逐行写入文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40474139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:35:20  来源:igfitidea点击:

Python : write text to file line by line

pythonfile

提问by Ashref

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?

我得到一个空文件。我怎样才能做到这一点?

回答by Ruler Of The World

This is how to print to a txt file:

这是打印到txt文件的方法:

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:

这是我编写的用于编写txt文件的程序:

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()

回答by Alex Hall

writelinesexpects 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 withstatement:

writelines需要一个可迭代的(例如一个列表)行,所以不要使用它。并且您需要关闭文件以保存更改,最好使用以下with语句完成:

with open("file", 'wb') as target:
    target.write(text)

回答by Mark Hannel

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.

您提供的代码会生成一个名为 file 的文件,其中包含所需的行。也许您打算将其另存为“file.txt”。此外,标志中的'b'in'wb'告诉代码以二进制模式写入文件(更多信息请点击此处)。'w'如果您希望文件可读,请尝试使用。

Finally it is best practice to use the withstatement when accessing files

最后,最好的做法是with在访问文件时使用该语句

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)

回答by Benny

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 withhas finished execution:

通过这种方式,文件在with执行完成后在缩进块之后关闭:

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

More info:

更多信息: