Home > Software engineering >  Converting every word or special character in a text file into a list?
Converting every word or special character in a text file into a list?

Time:04-02

What I have:

#text file:

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8">
<script id="polyfill-script-bundle">
</script>

What I want:

file = ['<!DOCTYPE html>\n', '<html lang="en" dir="ltr">\n', '<head>\n', '<meta http-equiv="content-type" content="text/html;charset=UTF-8">\n', '<script id="polyfill-script-bundle">\n', '</script>']

I plan to do this for an entire HTML text file, what is the best way to go about this?

CodePudding user response:

The code below retains the \n at the end of each line.

with open("filenamegoeshere.txt") as infile:
    as_list = infile.readlines()
print(as_list)

output

['<!DOCTYPE html>\n', '<html lang="en" dir="ltr">\n', '<head>\n', '<meta http-equiv="content-type" content="text/html;charset=UTF-8">\n', '<script id="polyfill-script-bundle">\n', '</script>']

CodePudding user response:

string.split('\n') sounds like the best thing here. Although be aware that this will remove the '\n's, if that isn't a problem this should be your best bet.

  • Related