0
    if choice==1:
    filename=input('Please enter file name: ')
    file=open(filename,'w')


print('Enter integers to be written to file and press enter when done.')
count=1
fox=1
while count >=1:
    filedata=str(input('Enter integer '+str(fox)+' : '))
    count+=1
    fox+=1
    file.write(filedata)
    if filedata=='':
       break

print(file)

I'm trying to print contents, however :<_io.TextIOWrapper name='das' mode='w' encoding='cp1252'> appears in its place.

Thanks

2 Answers2

1

You're not writing and reading the file properly.

Here is how to write to a file:

    filename = input('Please enter file name: ')
    with open(filename, 'w') as f:
        f.write("I love programming!")

Read a file line by line:

with open(filename) as f_obj:
    for line in f_obj:
        print(line.strip())

Given your code, you want to collect all the numbers in a list and then when the user finishes, write the list to a file.

You can do this with a while loop:

numbers = []
user_input = ""

# collect the numbers with a while loop and append them to a list
# as long as the input is not "e"

while user_input.lower() != "e":
    user_input = input ("Enter Number: ")
    if user_input != "e":
        numbers.append(str(user_input))

filename = input('Please enter file name: ')

with open(filename, 'w') as f:
    for num in numbers:
        # write each number to a line
        f.write(num)
        # add a new line after each number
        f.write("\n")
1

There are 2 fundamental problems with you program:

  1. file is a file descriptor. It's an object you can use to read the contents. You can do it by f.read() or line-by-line for line in file: print(line)

  2. You can't use the same file descriptor twice, as they are generally one-off (you hack it by changing the "cursor" place though). You should close the previous one, open a new one and then read it. I'd suggest using with open(filename) as file: (for reading) and with open(filename, "w") as file: (for writing) as they also ensure your file descriptors have been closed properly.

kszl
  • 1,203
  • 1
  • 11
  • 18