Python Forum

Full Version: Need help with writing to and reading from files?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
I am wondering for meaning to split the line by spaces into three values and then print these string objects as they are into the line. Just print the line
@wavic The Op asked
(Dec-20-2016, 07:45 PM)birdieman Wrote: [ -> ]When I read back the file I just wrote, do I 1) need to open the file, and 2) just change "write" to "read" -- so that I get the values to be associated with the correct variable names in the correct order?
That is why I have shown how to get the values back into the variables.

@birdieman How to use BBCode
The following code:
#Part 2
f = open("test.txt", "w")
your_start_age = 62
her_start_age = 61
start_year = 2017
for y in range(81):
   f.write('{}{}{}\n'.format(start_year, your_start_age, her_start_age))
   your_start_age += 1
   her_start_age += 1
   start_year += 1
f.close()

#Part 3

with open("test.txt", "r") as opened_file:
   for line in opened_file:
       start_year, your_start_age, her_start_age = line.split()
       print(start_year, your_start_age, her_start_age)
gives me this error for  "...... =.split() " line
Error:
ValueError: not enough values to unpack (expected 3, got 1)
sorry for all my ignorance
Your
f.write('{}{}{}\n'.format(start_year, your_start_age, her_start_age))
has not spaces between each {} so there is nothing to split on further down the code
change it to
f.write('{} {} {}\n'.format(startyear, yourstartage, herstartage))
as shown in earlier code.

Edit: Take this in mind that although I have shown how to get each value back into the variables, the values are still strings and not numbers, int or float could be used to convert them back depending on what type of numbers are needed.
works perfect -- thanks to all of you
Pages: 1 2