Python输出“无”当我尝试将文本线从输入文件复制到输出文件时,每行编号
我正在尝试阅读filea
,并将filea
的内容写入fileb
,将行号正确地固定在4列中,但是我继续获得“无”输出。
fileA = input("Enter the filename 1: ")
fileB = input("Enter the filename 2: ")
lineNo = 0
f = open(fileA, 'r')
g = open(fileB, 'w')
for line in f:
lineNo += 1
h = print(lineNo,">", line)
j = str(h).rjust(4, " ")
g.write(str(j))
I'm trying to read fileA
and write the contents of fileA
to fileB
while having the line numbers right-justified in 4 columns, but I keep getting "none" output.
fileA = input("Enter the filename 1: ")
fileB = input("Enter the filename 2: ")
lineNo = 0
f = open(fileA, 'r')
g = open(fileB, 'w')
for line in f:
lineNo += 1
h = print(lineNo,">", line)
j = str(h).rjust(4, " ")
g.write(str(j))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有一些错误,但正如指出的那样,打印说明造成了最大的问题。这是一个调试版本:
There were a few bugs, but as pointed out, the print statement was causing the most problem. Here is a debugged version:
打印
可以写入文件以及带有file = g
参数的控制台,但是您会发现print
还添加了newline而line
已经在字符串中有一个。使用end =''
来超越额外的行号。枚举
是编号迭代内容的不错功能。它默认为零,但是添加start = 1
将从一个数字编号。使用语句使用
来确保您的文件已关闭。如果不关闭文件,则在某些IDE中运行代码时可能不会将其冲洗到磁盘。
例子:
print
can write to a file as well as the console with afile=g
parameter, but you'll find thatprint
also adds a newline whileline
already has one in the string. Useend=''
to supress the extra line number.enumerate
is a nice function for numbering what is being iterated over. It defaults numbering from zero, but addingstart=1
will number from one.Use
with
statements to make sure your files are closed. Without closing the file, it might not be flushed to disk when running your code in some IDEs.Example: