Python Forum
Need help with writing to and reading from files?
Thread Rating:
  • 1 Vote(s) - 1 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Need help with writing to and reading from files?
#1
I am new to this forum and python, as you will discover.  I am trying to learn how to write variables to a file that I can later read back.  My code is below -- sorry, I do not know how to do 'code tags' (I will learn). 

I need to know what is wrong with the statement "f.write (startyear, yourstartage, herstartage).  I am using PyCharm text editor, and to no really know how to use it either, so please bear with me.
yourstartage = 62

herstartage = 61
startyear = 2017

print("Year", "Your", "Her")
print("\t ", "Age", "Age")
for i in range(81):
   print(startyear, yourstartage, herstartage)
   yourstartage += 1
   herstartage += 1
   startyear += 1

f = open("test.txt", "wb")
for y in range(81):
   f.write(startyear,yourstartage,herstartage)
   yourstartage += 1
   herstartage += 1
   startyear += 1
   f.close()
thanks for looking
Reply
#2
try this:
    f.write('{} {} {}'.format(startyear, yourstartage, herstartage))
Reply
#3
thank you -- will try it.

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?

thanks again
Reply
#4
At the moment you have an error from the line
f.write(startyear,yourstartage,herstartage)
When you have an error you should state the error trace back in your question
The error you get is
Error:
TypeError: write() takes exactly 1 argument (3 given)
you are passing write 3 arguments when it will only accept one argument that has a str value.
Change your write line to
 f.write('{} {} {}\n'.format(startyear,yourstartage,herstartage))
so the format combines all your arguments into one string, the {} are replaced by them and the \n adds a newline to the end.
You will also get the error
Error:
TypeError: 'str' does not support the buffer interface
after changing this because you need to change the open flag
f = open("test.txt", "wb")
to just w
f = open("test.txt", "w")
The
f.close()
needs dedenting back to the first coloumn.
Reply
#5
thanks --
Reply
#6
When reading back the file the values will be a string on each line, to get back to the variables the formatting that was done will need reversing.
In the following code
  • with is used to open the file without needing to call close when finished with.
  • for iterates each line into the line variable.
  • strip removes the \n from the end of the line, split separates the line where there is a space(defaults to space)
with open('test.txt', 'r') as opened_file:
    for line in opened_file:
        startyear, yourstartage, herstartage = line.strip().split()
        print(startyear, yourstartage, herstartage)
Reply
#7
@Yoriz, Doesn't split() remove '\n'? Isn't '\n' a whitespace?

In [3]: import string

In [4]: string.whitespace
Out[4]: ' \t\n\r\x0b\x0c'

In [5]: 
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#8
Yea possibly
Edit:
As pointed out above strip is not necessary in the following line
startyear, yourstartage, herstartage = line.strip().split()
It can be just
startyear, yourstartage, herstartage = line.split()
Reply
#9
I made the suggested changes, and get no errors (that I can tell), but the last part of the code does not do what I want it to, which is to read the file I just wrote to, and print out what was read (there should be 80 rows of three variables/values per row).  With the code I have,  I assumed the print statement would execute each time the file was read, ie, read a row, print it, read a row, print it, etc. (nothing prints out)
f = open("test.txt", "w")
yourstartage = 62
herstartage = 61
startyear = 2017
for y in range(81):
   f.write('{}{}{}\n'.format(startyear, yourstartage, herstartage))
   yourstartage += 1
   herstartage += 1
   startyear += 1


with open("test.txt", "r") as opened_file:
   for line in opened_file:
       startyear, yourstartage, herstartage = line.split()
       print(startyear, yourstartage, herstartage)
I looked on the forum site to find how to do code tags but could not find reference. sorry.  thanks for all of your help - no more questions today
Reply
#10
You didn't close the file, you need to add f.close() after the first loop.
A better way is to use with (which doesn't require a close):
with open("test.txt", "w") as f:
    for y in range(81):
        ...
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Writing into 2 text files from the same function paul18fr 4 1,668 Jul-28-2022, 04:34 AM
Last Post: ndc85430
  Using .hdf5 files only once they are finished writing pyhill00 7 2,783 Nov-25-2021, 06:01 PM
Last Post: pyhill00
  Fastest Way of Writing/Reading Data JamesA 1 2,181 Jul-27-2021, 03:52 PM
Last Post: Larz60+
  Reading Multiple text Files in pyhton Fatim 1 1,911 Jun-25-2021, 01:37 PM
Last Post: deanhystad
  Trouble reading files using pyexcel codebeacon 2 2,180 Feb-08-2021, 05:53 AM
Last Post: codebeacon
  Reading txt files in ssh server. therenaydin 6 4,125 Aug-06-2020, 05:17 AM
Last Post: ndc85430
  How to stop the reading of files Laplace12 4 2,349 Jul-27-2020, 04:07 PM
Last Post: Gribouillis
  How can I speed up my openpyxl program reading Excel .xlsx files? deac33 0 3,387 May-04-2020, 08:02 PM
Last Post: deac33
  Other modules for reading audio files? jedzz 0 1,593 Mar-25-2020, 11:07 PM
Last Post: jedzz
  Error With Reading Files In Directory And Calculating Values chascp 2 2,425 Feb-15-2020, 01:57 PM
Last Post: chascp

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020