[英]How do I read a text file as a string?
Below are the codes I have tried to read the text in the text file in a method called check_keyword()
下面是我尝试在名为check_keyword()
的方法中读取文本文件中的文本的代码
def check_keyword():
with open(unknown.txt, "r") as text_file:
unknown = text_file.readlines()
return unknown
This is how i called the method:这就是我调用该方法的方式:
dataanalysis.category_analysis.check_keyword()
The text in the text file:文本文件中的文本:
Hello this is a new text file
There is no output for the method above :((上面的方法没有输出:((
text_file.readlines()
returns a list of strings containing the lines in the file. text_file.readlines()
返回包含文件text_file.readlines()
的字符串列表。 If you want only a string, not a list of the lines, use text_file.read()
instead.如果您只需要一个字符串,而不是行列表,请改用text_file.read()
。
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).您的代码中还有另一个问题,您正在尝试打开unknown.txt
,但您应该尝试打开'unknown.txt'
(带有文件名的字符串)。
You can do this as follows:您可以按如下方式执行此操作:
with open("foo","r") as f:
string = f.read()
而不是text_file.readlines()
使用text_file.read()
它将以字符串格式而不是列表为您提供文件内容。
The code is just a working code based on all the above answers.该代码只是基于上述所有答案的工作代码。
def check_keyword():
with open("unknown.txt", "r") as text_file:
unknown = text_file.read()
return unknown
check_keyword()
Actually i have made a whole lib to make that work easy for all实际上,我已经制作了一个完整的库,以使所有人都能轻松完成这项工作
from filemod import reader
data=reader("file.txt))
print(data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.