Python:通过lin将文本写入文件行

2024-04-26 03:03:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试着写一些文本到一个文件,下面是我试过的:

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)

我得到一个空文件。 我该怎么做?


Tags: and文件ofthetext文本targetis
3条回答

以下是如何打印到txt文件:

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

另一种方法是:

with open('Exported.txt', 'w') as file:
   file.write("Text to write to 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()

通过这种方式,您应该直接关闭文件:

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

这样,在with完成执行后,在缩进块之后关闭文件:

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

更多信息:

writelines需要一个iterable(例如一个列表)行,所以不要使用它。您需要关闭文件以保存更改,最好使用with语句:

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

相关问题 更多 >