-2

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?

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
  • 1
    Does this answer your question? [How to read a file line-by-line into a list?](https://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list) –  Apr 01 '22 at 15:37
  • @SembeiNorimaki partly but that question does not satisfy – Flamenco33 Apr 01 '22 at 15:38
  • 1
    how does not satisfy your question? you are storing each line as an element in a list –  Apr 01 '22 at 15:38

2 Answers2

0

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.

Jacob
  • 135
  • 2
  • 12
0

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>']
Edo Akse
  • 4,051
  • 2
  • 10
  • 21