Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()

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 :((

like image 839
School Avatar asked Nov 08 '18 09:11

School


People also ask

Which function can be used to read a text file as a string?

Use the ReadAllText method of the My. Computer. FileSystem object to read the contents of a text file into a string, supplying the path.

How do you convert text to string in Python?

To convert an integer to string in Python, use the str() function. This function takes any data type and converts it into a string, including integers. Use the syntax print(str(INT)) to return the int as a str , or string.


2 Answers

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.

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).

like image 173
iz_ Avatar answered Oct 25 '22 12:10

iz_


You can do this as follows:

with open("foo","r") as f:
    string = f.read()
like image 42
power.puffed Avatar answered Oct 25 '22 14:10

power.puffed