newbie16 newbie16 - 1 month ago 15
Python Question

python file read, write line by line

I am studying python file I/O. I made a simple program(main.py).

My goal is read line by line and write line by line.

fstream = open("input2.txt", 'r');
line = fstream.readline()
while line:
print(line);
line = fstream.readline()

fstream.close()


below are my
input2.txt
file

start.
hello world.
hello python.
I am studying file I/O in python
end.


when I run python program


python main.py


Then, result is ...

start.

hello world.

hello python.

I am studying file I/O in python

end.


That is not the same as I expected.

So I modified the main.py

fstream = open("input2.txt", 'r');
line = fstream.read().split("\n")
while line:
print(line);
line = fstream.read().split("\n")

fstream.close()


However my program diged into infinite loop.

picture of infinite loop

To solve this problem what should I do?




The result I expected is the following.

start.
hello world.
hello python.
I am studying file I/O in python
end.

Answer

The print function will automatically add a new line character. So

print msg

will print content of variable msg followed by a new line

If you do not want python to print the trailing new line, you have to add a comma to the end. This will print msg without the trailing newline. And if msg already has a new line which is the case when reading new lines from a file, you will see a single new line in place of double new lines.

print msg,

If you are using python 3 where print is called as a function, you can specify the end argument. See https://docs.python.org/3/library/functions.html#print

print(msg, end = '')
Comments