如何将文本文件作为字符串读取? [英] How do I read a text file as a string?
本文介绍了如何将文本文件作为字符串读取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下是我尝试在名为 check_keyword()
def check_keyword():
with open(unknown.txt, "r") as text_file:
unknown = text_file.readlines()
return unknown
我是这样调用方法的:
dataanalysis.category_analysis.check_keyword()
文本文件中的文本:
Hello this is a new text file
上述方法没有输出:((
There is no output for the method above :((
推荐答案
text_file.readlines()
返回包含文件中行的字符串列表.如果您只需要一个字符串,而不是行列表,请改用 text_file.read()
.
text_file.readlines()
returns a list of strings containing the lines in the file. If you want only a string, not a list of the lines, use text_file.read()
instead.
您的代码中还有另一个问题,您正在尝试打开 unknown.txt
,但您应该尝试打开 'unknown.txt'
(一个字符串与文件名).
You also have another problem in your code, you are trying to open unknown.txt
, but you should be trying to open 'unknown.txt'
(a string with the file name).
这篇关于如何将文本文件作为字符串读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文