School
School

Reputation: 803

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

Upvotes: 22

Views: 59547

Answers (5)

kshitijjathar
kshitijjathar

Reputation: 1

Actually i have made a whole lib to make that work easy for all

from filemod import reader
data=reader("file.txt"))
print(data)

Upvotes: -3

Fong Sow Leong
Fong Sow Leong

Reputation: 48

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

Upvotes: 2

iz_
iz_

Reputation: 16583

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

Upvotes: 26

power.puffed
power.puffed

Reputation: 445

You can do this as follows:

with open("foo","r") as f:
    string = f.read()

Upvotes: 33

bak2trak
bak2trak

Reputation: 1120

Instead of text_file.readlines() use text_file.read() which will give you contents of files in string format rather than list.

Upvotes: 3

Related Questions