Skip to content

Instantly share code, notes, and snippets.

@hygull
Last active December 16, 2018 04:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hygull/e26351a65f7ea8103cd85eb5971190a5 to your computer and use it in GitHub Desktop.
Save hygull/e26351a65f7ea8103cd85eb5971190a5 to your computer and use it in GitHub Desktop.
stackoverflow, getting file contents either in a line / as a list of words

https://stackoverflow.com/questions/53799391/input-file-example/53799514#53799514

16 Dec 2018, Sun

You are missing number of things in your code, actually that is not a good way to get the file contents in one line.

This is a simple example that will give you both, a single line and a list of words.

raw_file.txt

My intension was to tell you the secret of my life and I wish you will like it.

in_one_line.py

import re

with open("rw_file.txt", encoding="utf-8") as f:
	lines = f.read();
	s = re.sub(r'\s+', ' ', lines)

words = s.split()

print(s) 
# My intension was to tell you the secret of my life and I wish you will like it.

print(words)
# ['My', 'intension', 'was', 'to', 'tell', 'you', 'the', 'secret', 'of', 'my', 'life', 'and', 'I', 'wish', 'you', 'will', 'like', 'it.']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment