简体   繁体   English

从python中的文本文件读取文本

[英]Reading text from a text file in python

I am having trouble trying to figure out how to import text from a text file easily or at least a memorable method. 我在尝试弄清楚如何轻松地或者至少是一种令人难忘的方法从文本文件导入文本时遇到了麻烦。 I am trying to make a program that insults the user (for school), that brings in a word/s from one text file, adds another word/s from the second file and the final word/s from the third text file... 我正在尝试制作一个侮辱用户(针对学校)的程序,该程序从一个文本文件中引入一个单词,从第二个文件中添加另一个单词,并从第三个文本文件中添加最终单词。 。

I am having trouble finding a way of coding to do this...I have the random number up and running to pick the text I just need to know how to access strings or text in a text file. 我很难找到一种编码方式来执行此操作...我已经启动并运行随机数来选择文本,我只需要知道如何访问文本文件中的字符串或文本即可。

The easiest way is to use the with statement. 最简单的方法是使用with语句。 It takes care of closing the file for you. 它会为您关闭文件。

with open("file.txt") as f:
    for line in f:
        # do something with line

Or read the data into directly into a list: 或将数据直接读入列表:

with open("file.txt") as f:
    lines = list(f)
# do something with lines

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM