Python输出“无”当我尝试将文本线从输入文件复制到输出文件时,每行编号

发布于 2025-02-10 10:35:42 字数 415 浏览 4 评论 0原文

我正在尝试阅读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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

驱逐舰岛风号 2025-02-17 10:35:42

有一些错误,但正如指出的那样,打印说明造成了最大的问题。这是一个调试版本:

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 = str(lineNo).rjust(4) + ">" + line
    g.write(h)

There were a few bugs, but as pointed out, the print statement was causing the most problem. Here is a debugged version:

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 = str(lineNo).rjust(4) + ">" + line
    g.write(h)
爱她像谁 2025-02-17 10:35:42

打印可以写入文件以及带有file = g参数的控制台,但是您会发现print还添加了newline而line已经在字符串中有一个。使用end =''来超越额外的行号。

枚举是编号迭代内容的不错功能。它默认为零,但是添加start = 1将从一个数字编号。

使用语句使用来确保您的文件已关闭。如果不关闭文件,则在某些IDE中运行代码时可能不会将其冲洗到磁盘。

例子:

fileA = input("Enter the filename 1: ")
fileB = input("Enter the filename 2: ")
with open(fileA, 'r') as f, open(fileB, 'w') as g:
    for lineNo,line in enumerate(f, start=1):
        print(f"{lineNo:>4}> {line}", end='', file=g)

print can write to a file as well as the console with a file=g parameter, but you'll find that print also adds a newline while line already has one in the string. Use end='' to supress the extra line number.

enumerate is a nice function for numbering what is being iterated over. It defaults numbering from zero, but adding start=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:

fileA = input("Enter the filename 1: ")
fileB = input("Enter the filename 2: ")
with open(fileA, 'r') as f, open(fileB, 'w') as g:
    for lineNo,line in enumerate(f, start=1):
        print(f"{lineNo:>4}> {line}", end='', file=g)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文