繁体   English   中英

python文件读取,逐行写入

[英]python file read, write line by line

我正在研究python文件I / O。 我做了一个简单的程序( main.py )。

我的目标是逐行读取并逐行写入。

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

fstream.close()

以下是我的input2.txt文件

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

当我运行python程序时

python main.py

然后,结果是...

start.

hello world.

hello python.

I am studying file I/O in python

end.

那与我预期的不同。

所以我修改了main.py

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

fstream.close()

但是我的程序陷入了无限循环。

无限循环的图片

为了解决这个问题,我该怎么办?


我预期的结果如下。

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

打印功能将自动添加新的换行符。 所以

print msg

将打印变量msg的内容,然后换行

如果您不希望python打印尾随的新行,则必须在末尾添加逗号。 这将在没有尾随换行符的情况下输出味精。 并且如果msg已经有一个新行(当从文件中读取新行时就是这种情况),您将看到一个新行代替了两个新行。

print msg,

如果使用的Python 3将print作为函数调用,则可以指定end参数。 参见https://docs.python.org/3/library/functions.html#print

print(msg, end = '')

首先,使用with语句打开文件,这样就无需显式关闭文件。 其次,不要为此使用while循环; 您可以直接遍历文件。 第三,使用rstrip方法从您读取的行中删除任何尾随空格(或rstrip('\\n')仅删除尾随换行符):

with open("input2.txt", 'r') as fstream:
    for line in fstream:
        line = line.rstrip('\n')
        print(line)

除上述答案外; 您也可以使用.splitlines()

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

fstream.close()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM