语言:python(版本:3.7.3) 熟练程度:新手
我想删除文件每行中的所有前导空格和尾随空格。因此,我使用了内部构建方法'strip()',它几乎可以完成这项工作,但是我的代码从文件底部开始不活动,这导致文件中的行重复。任何援助都将对实现这一目标大有帮助。在
我的代码如下:
class filecorrection:
def removeLeadingandTrailingSpacesinaFile(self, fromFile):
with open(fromFile, 'r+') as file:
lines = file.readlines()
for line in lines:
file.write(line.strip() + "\n")
cm = filecorrection()
cm.removeLeadingandTrailingSpacesinaFile("filepath")
我试图使用seek方法将指针放在文件的开头,但是没有得到完美的输出。在
^{pr2}$应输入:(删除尾部和前导空格)
<book id="bk105">
<author>Corets, Eva</author>
<title>The Sundered Grail</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>testing</publish_date>
</book>
实际:
<book id="bk105">
<author>Corets, Eva</author>
<title>The Sundered Grail</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>testing</publish_date>
</book><book id="bk105">
<author>Corets, Eva</author>
<title>The Sundered Grail</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>testing</publish_date>
</book>
代码的问题:
另外,尝试对您读取的行和您创建的新行使用不同的变量。这是一个很好的做法。在
请参阅下面的更新代码。在
你可以像这样打开文件两次
而不是尝试同时读写文件。以写模式打开文件(
w
)会将文件截断为零长度并从头开始写入。在您可以使用另一个文件来存储中间结果,然后用它替换原始文件。在这里,您正在读写同一个文件。在
相关问题 更多 >
编程相关推荐