line.strip()方法澄清 admin 2023-01-29 17:42:01 篇首语:本文由小编为大家整理,主要介绍了line.strip()方法澄清相关的知识,希望对你有一定的参考价值。 nS。JSzhUOER。cOm语言:python(版本:3.7.3)熟练程度:新手我想删除文件每行中的所有前导和尾随空格。因此我使用了in-build方法"strip()"来完成这项工作,但我的代码从文件底部开始执行,导致文件中的行重复。任何援助对实现目标都非常有帮助。我的代码如下:class filecorrection: def removeLeadingandTrailingSpacesinaFile(self, fromFile): with open(fromFile, "r+") as file: lines = file.readlines() for line in lines: file.write(line.strip() + "")cm = filecorrection()cm.removeLeadingandTrailingSpacesinaFile("filepath")我试图使用搜索方法将指针放在文件的开头,但没有得到完美的输出。class filecorrection:def removeLeadingandTrailingSpacesinaFile(self, fromFile): with open(fromFile, "r+") as file: lines = file.readlines() **file.seek(0)** for line in lines: file.write(line.strip() + "")cm = filecorrection()cm.removeLeadingandTrailingSpacesinaFile("filepath")预期:(删除尾随和前导空格)Corets, EvaThe Sundered GrailFantasy5.95testingnS。JSzhUOER。cOm实际: Corets, Eva The Sundered Grail Fantasy nS。JSzhUOER。cOm5.95 testing Corets, EvaThe Sundered GrailFantasy5.95testing 答案您可以像这样打开文件两次class filecorrection: def removeLeadingandTrailingSpacesinaFile(self, fromFile): lines = [] with open(fromFile, "r") as file: lines = file.readlines() with open(fromFile, "w") as file: for line in lines: file.write(line.strip() + "")cm = filecorrection()cm.removeLeadingandTrailingSpacesinaFile("test.xml")而不是试图同时读取和写入文件。以写入模式(w)打开文件会将文件截断为零长度并从头开始写入。 另一答案代码问题:您正在尝试写入相同的输入文件。nS。JSzhUOER。cOm还尝试对您阅读的行和您创建的新行使用不同的变量。这是一个很好的做法。请参阅下面的更新代码with open(fromFile, "r+") as infile, open(writeFile, "w") as outfile: for line in infile: new_line = line.rstrip("").strip() #now write the new line to out file outfile.write(new_line + "") 另一答案nS。JSzhUOER。cOm您可以使用另一个文件来存储中间结果,然后用它替换原始文件。在这里,您正在阅读和写入同一个文件。import pathlibimport shutilclass filecorrection: def removeLeadingandTrailingSpacesinaFile(self, fromFile): parent_path=pathlib.Path(fromFile).parent # Make sure you have permissions to create a file. If not # you can save intermediate results in memory instead. temp_file = str(parent_path / "temp_file") with open(fromFile, "r+") as file, open(temp_file, "w+") as temp: for line in file: temp.write(line.strip()+"") shutil.move(temp_file, fromFile)cm = filecorrection()cm.removeLeadingandTrailingSpacesinaFile("file.txt") 以上是关于line.strip()方法澄清的主要内容,如果未能解决你的问题,请参考以下文章 大数据概述前世今生处理流程学习路线开发工具详解 Latex 论文elsevier,手把手如何用Latex写论文 您可能还会对下面的文章感兴趣: 相关文章 商丘私人空放联系方式_基本资料审核后快速就能放款平台 济宁私人借钱24小时在线,5万以上级别的贷款|无抵押个人借贷|秒下| 湖州空放私借2小时放款—身无分文借贷100%直接放款 宜昌纯私人放款微信电话——马上为您安排信贷服务+当日到账 蚌埠24小时私人放款联系方式随借随到-做生意借贷|应急周转|大额优先| 遵义空放借钱贷款联系电话:走投无路申请放款马上就到账 绵阳专业空放贷款私人联系方式,不看过往|先贷后放|马上拿钱| 德州附近个人放款电话号码多少:不审核+随借随还+当日成功+直接到账