john
john

Reputation: 2662

How to use python markdown to process a file that is read in?

I have a file myfile.txt.

hello

And I have the following script:

#!/usr/bin/python 
import markdown

f = open('myfile.txt', 'r') 
f.read() 
htmlmarkdown=markdown.markdown(f)

I got the:

AttributeError: 'file' object has no attribute 'strip'

What I should do to make a success?

Upvotes: 5

Views: 24635

Answers (2)

thagorn
thagorn

Reputation: 747

pyDog's answer is correct. Your problem is that f is a file object. You need to pass markdown a string. Calling just f.read() will put the file cursor at the end of the file but won't put the file contents in a string like you need.

f = open('myfile.txt', 'r')
fileString = f.read()
htmlmarkdown=markdown.markdown( fileString )

If you look at the error you got:

 AttributeError: 'file' object has no attribute 'strip'

This is because you passed a 'file' object (namely f) to markdown and it tried to call the string function strip() which has no meaning for 'file' objects.

Upvotes: 4

pyDog
pyDog

Reputation: 166

Try this:

f = open('myfile.txt', 'r')
htmlmarkdown=markdown.markdown( f.read() )

Upvotes: 15

Related Questions