Python : write text to file line by line
本问题已经有最佳答案,请猛点这里访问。
我正在尝试将一些文本写入一个文件,下面是我的尝试:
1 2 3 4 5 | 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) |
我得到一个空文件。我该怎么做?
这是如何打印到TXT文件:
1 2 3 | file = open("Exported.txt","w") file.write("Text to write to file") file.close() #This close() is important |
另一种方法是:
1 2 | with open('Exported.txt', 'w') as file: file.write("Text to write to file") |
这是我编写的一个用于写入TXT文件的程序:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | 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 ") start() def create(): print() filename = input("What do you want the file to be called? ") 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(" ") 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 ") start() else: print("Error") start() |
通过这种方式,您应该直接关闭文件:
1 2 3 | target = open("filename.txt", 'w') target.writelines(text) target.close() |
这样,在
1 2 | with open("filename.txt","w") as fh: fh.write(text) |
更多信息:
- http://www.python-course.eu/python3_file_management.php
您提供的代码将生成一个名为file的文件,其中包含所需的行。也许您打算将其保存为"file.txt"。另外,
最后,在访问文件时使用
1 2 3 4 5 | 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) |
1 2 | with open("file", 'wb') as target: target.write(text) |