'Converting every word or special character in a text file into a list?
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?
Solution 1:[1]
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>']
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Edo Akse |
| Solution 2 | Jacob |
