0

I did example 16 and decided to keep adding to it. I wanted after rewriting the contents to be able to read it right after.

from sys import argv

script, file = argv

print "Do you want to erase the contents of %r?" % file
print "If yes hit RETURN, or CTRL-C to abort."

raw_input()

target = open(file, 'w')

target.truncate()

print "Now you can type new text to the file one line at a time."

line1 = raw_input("line1: ")
line2 = raw_input("line2: ")
line3 = raw_input("line3: ")

print "The data will now be written to the file."

target.write(line1)
target.write('\n')
target.write(line2)
target.write('\n')
target.write(line3)
target.write('\n')

print "Data has been added to the file."

new_data = open(target)

print new_data.read()

After running it when I get to this point I get the syntax error need string to buffer, file found. I know from the beginning the file was opened in 'w' (write mode) so I also tried this:

new_data = open(target, 'r')

print new_data.read()
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
pynoob00
  • 29
  • 1
  • 4

3 Answers3

1

If you'd like to both read and write a file, use the appropriate mode, such as 'w+', which is similar to 'w' but also allows reading. I would also recommend the with context manager so you don't have to worry about closing the file. You don't need truncate(), either, as explained in this question.

with open(file, 'w+') as target:
    # ...your code...

    # new_data = open(target) # no need for this
    target.seek(0) # this "rewinds" the file
    print target.read()
Community
  • 1
  • 1
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
0

The answer is in the error message, you are trying to pass a file into open() function whereas the first parameter should be a string - a file-name/path-to-file. This suppose to work:

new_data = open(file, "r")
print new_data
Yury
  • 56
  • 3
0

It is more preferred to use the "open resource as" syntax since it automatically flushes and closes resources which you need to do after writing to a file before you can read from it (without seek-ing to the beginning of the file).

print "Do you want to erase the contents of %r?" % file
print "If yes hit RETURN, or CTRL-C to abort."

raw_input()

with open(file, 'w+') as target:

    target.truncate()

    print "Now you can type new text to the file one line at a time."

    line1 = raw_input("line1: ")
    line2 = raw_input("line2: ")
    line3 = raw_input("line3: ")

    print "The data will now be written to the file."

    target.write(line1)
    target.write('\n')
    target.write(line2)
    target.write('\n')
    target.write(line3)
    target.write('\n')

print "Data has been added to the file."

with open(file) as new_data:
    print new_data.read() 
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245