In the line:
Jobs = ()
you create a tuple
. A tuple
is immutable and has no methods to add, remove or alter elements. You probably wanted to create a list
(lists have an .append
-method). To create a list use the square brackets instead of round ones:
Jobs = []
or use the list
-"constructor":
Jobs = list()
However some suggestions for your code:
open
ing a file requires that you close
it again. Otherwise Python will keep the file handle as long as it is running. To make it easier there is a context manager for this:
with open('Jobs.txt') as openFile:
x = 1
while x != 0:
Stuff = openFile.readline(x)
if Stuff != '':
Jobs.append(Stuff)
else:
x = 0
As soon as the context manager finishes the file will be closed automatically, even if an exception occurs.
It's used very rarely but iter
accepts two arguments. If you give it two arguments, then it will call the first each iteration and stop as soon as the second argument is encountered. That seems like a perfect fit here:
with open('Jobs.txt') as openFile:
for Stuff in iter(openFile.readline, ''):
Jobs.append(Stuff)
I'm not sure if that's actually working like expected because openFile.readline
keeps trailing newline characters (\n
) so if you want to stop at the first empty line you need for Stuff in iter(openFile.readline, '\n')
. (Could also be a windows thingy on my computer, ignore this if you don't have problems!)
This can also be done in two lines, without creating the Jobs
before you start the loop:
with open('Jobs.txt') as openFile:
# you could also use "tuple" instead of "list" here.
Jobs = list(iter(openFile.readline, ''))
Besides iter
with two arguments you could also use itertools.takewhile
:
import itertools
with open('Jobs.txt') as openFile:
Jobs = list(itertools.takewhile(lambda x: x != '', openFile))
The lambda
is a bit slow, if you need it faster you could also use ''.__ne__
or bool
(the latter one works because an empty string is considered False
):
import itertools
with open('Jobs.txt') as openFile:
Jobs = list(itertools.takewhile(''.__ne__, openFile))