To read a file and separate each line by whitespace, you can use the following code:
main.py182 chars5 lines
Here's what each line of the code does:
with open('filename.txt', 'r') as file:
opens the file named filename.txt
in read mode and assigns it to the variable file
. The with
statement ensures that the file is automatically closed when the block of code is exited.for line in file:
loops over each line in the file
object.line.strip()
removes any leading or trailing whitespace from the line.line.strip().split()
splits the line into a list of words, using whitespace as the delimiter. The resulting list is assigned to the words
variable.You can then use the words
variable to access each word in the line, for example:
main.py155 chars6 lines
Note that if you want to read a file with a different delimiter (e.g. commas), you can pass that delimiter as an argument to the split()
method, like this: line.strip().split(',')
.
gistlibby LogSnag