Reputation: 155
Why does this split not work? When I run the code split_1
is not printed.
with open ('r_3exp', 'a+') as file_1:
choice = input ('1 (write) or 2? ')
number = input ('What number?')
if choice == '1':
file_1.write ('\n')
file_1.write ('Here are some numbers : 1233 8989' + ' ' + number)
else:
for line in file_1:
split_1 = line.split (":")
print (split_1)
Upvotes: 0
Views: 87
Reputation: 9846
This is because you are opening your file up in a+
mode.
a+
allows for both reading and appending to a file. On the surface, this sounds ideal for what you want. However, there are some subtle tricky mechanics you've missed about this mode:
A file opened in a+
is automatically opened at the end of the file. In other words, you are no longer reading from the beginning of the file, but rather starting from the very end of it.
As a consequence, when you do for line in file_1
, you are actually starting to read from the character at the very end of the file. Since there is, by definition, nothing there, line
returns an empty string and line.split(':')
is also empty.
To correct this, it is more prudent to reorganise your code a little to use either r
mode or a
mode:
choice = input("1 (write) or 2? ")
if choice == "1":
number = input("What number? ")
with open("r_3exp","a") as file_1:
file_1.write ('\n')
file_1.write ('Here are some numbers : 1233 8989' + ' ' + number)
elif choice == "2":
with open("r_3exp","r") as file_1:
for line in file_1:
split_1 = line.split (":")
print (split_1)
r
opens up your file to start reading from the first character of the file, rather than from the last.
I would still recommend the above code for someone using Python 2.7, but with one additional caveat: input()
returns None
in Python 2.7, because it's actually evaluating the input as a Python command. The correct function to use in Python 2.7 is raw_input()
, which correctly returns a string.
Upvotes: 2