-1

This is my code

fw = open('input.txt', 'w')
fw.write(input())
fw.close()
fr = open('input.txt', 'r')
for y in fr:
    print(y)
fr.close()

When the user writes into the file. How can he go to the next line?

Whenever I hit enter it accepts only one line and does not go to the next line.

example: When I run this code, I input

1 2 3 4

The output is same as input. But I want it to be written as

1
2
3
4

in the input.txt file.

I tried the following and did not work.

  1. fw.write(input() + "\n")
  2. fw.write(input("\n")
fredtantini
  • 15,966
  • 8
  • 49
  • 55
Rajath
  • 1,306
  • 2
  • 10
  • 18

3 Answers3

2

You need a loop. Try this:

fw = open('input.txt', 'w')
while 1:
    info = input('enter stop to stop:')
    if info == 'stop':
        break
    fw.write(info)

fw.close()
fr = open('input.txt', 'r')

for y in fr:
    print(y, end='')
fr.close()
Stephen Lin
  • 4,852
  • 1
  • 13
  • 26
1

Whenever i hit enter it accepts only one line and does not go to the next line.

Yes, input take only 1 line as input.

You can either, use a loop until a certain response is given, or use split to split your input and then write each item on the list on a new line:

fw.write('\n'.join(input().split(' ')))

or

userInput = input()
for line in userInput.split(' '):
    fw.write(line)
Community
  • 1
  • 1
fredtantini
  • 15,966
  • 8
  • 49
  • 55
  • you could use `.split()` instead of `.split(' ')` to allow arbitrary whitespace such as tabs (`'\t'`). You should append `'\n'` in the second code example or use `print(line, file=fw)` – jfs Jan 12 '15 at 08:38
1

To print each whitespace-separated item in the input string on its own line:

print(*input().split(), sep='\n', file=fw)
jfs
  • 399,953
  • 195
  • 994
  • 1,670