我正在努力学习Python,用Power和NotePad++艰难地学习Python。
我已经到了使用.readline()的部分,我注意到函数中第一个参数的第一个字符被删除或用空格覆盖。我知道已经有一个问题似乎可以回答这个问题(Python .readline()),但是由于我对Powershell完全陌生,所以我不知道如何在这两个问题中任意一个篡改和更改设置。
我编写的执行脚本(称为new 1.py)如下所示:
from sys import argv
script, input_filename = argv
def foo (arg1,arg2,arg3):
print arg1,arg2,arg3.readline()
def bar (arg1, arg2, arg3):
print arg2,arg1,arg3.readline()
open_input_file=open(input_filename)
foo ("Text1",1,open_input_file)
foo ("Text2",2,open_input_file)
bar ("Text3",3,open_input_file)
bar ("Text4","4",open_input_file)使用包含文本的test1.py文件:
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6我的产出如下:
$ python "new 1.py" test1.py
ext1 1 ☐ Line 1
ext2 2 Line 2
Text3 Line 3
Text4 Line 4我期望的输出是:
$ python "new 1.py" test1.py
Text1 1 Line 1
Text2 2 Line 2
3 Text3 Line 3
4 Text4 Line 4请有人解释一下如何让.readline()在不擦除或覆盖第一个字符的情况下(用空格)来读取行吗?为什么在输出的大写字母L前面有一个白色的盒子?
发布于 2015-09-07 19:53:22
在得到了theamk、jonrsharpe、Martijn Pieters和Nitu的建议后,我尝试了以下脚本:
from sys import argv
script, input_filename = argv
def foo (arg1,arg2,arg3):
print arg1,arg2,arg3.readline().strip("\r\n")
def bar (arg1, arg2, arg3):
print arg2,arg1,repr(arg3.readline().strip("\r\n"))
open_input_file=open(input_filename)
foo ("Text1",1,open_input_file)
foo ("Text2",2,open_input_file)
bar ("Text3",3,open_input_file)
bar ("Text4","4",open_input_file)并编写了一个新的test2.py文件,其中包含了与'test1.py‘文件中相同的文本,但这一次我手工输入了所有六行代码(而不是从上一份文档中粘贴文本)
我现在的产出如下:
$ python "new 1.py" test2.py
Text1 1 Line 1
Text2 2 Line 2
3 Text3 ´Line 3´
4 Text4 ´Line 4´这正是我所期望的这个脚本的输出。非常感谢你们帮助我解决这个问题!
发布于 2015-09-07 18:52:36
readline()方法从文件中读取整行。字符串中保留一个尾换行符。你不用再放两遍了。如果将其放入,则将得到传递的结果,如line2、line4、line6和arg3的空字符串。
为定义的方法尝试以下代码。
def foo (arg1,arg2,arg3):
print arg1,arg2,arg3.readline().rstrip("\n")
def bar (arg1, arg2, arg3):
print arg2,arg1,arg3.readline().rstrip("\n")发布于 2015-09-04 16:07:42
readline()输出始终包含末尾的行尾字符。您可以使用repr()函数看到它们:
print repr(bl.readline())在大多数情况下,你想要剥去它们:
bl.readline().rstrip('\r\n')如果您不关心行的开头/结尾处的常规空格,则可以将其简化为:
bl.readline().strip()https://stackoverflow.com/questions/32400639
复制相似问题