当前位置: 首页 > 面试题库 >

读/写文本文件

毛淳
2023-03-14
问题内容

我正在尝试更改文本文件中的某些行,而不影响其他行。这就是文本文件“ text.txt”中的内容

this is  a test1|number1
this is a test2|number2
this is a test3|number2
this is a test4|number3
this is a test5|number3
this is a test6|number4
this is a test7|number5
this is a test8|number5
this is a test9|number5
this is a test10|number5

我的目标是更改第4行和第5行,但其余部分保持不变。

mylist1=[]
for lines in open('test','r'):
    a=lines.split('|')
    b=a[1].strip()
    if b== 'number3':
        mylist1.append('{}|{} \n'.format('this is replacement','number7'))
    else:
         mylist1.append('{}|{} \n'.format(a[0],a[1].strip()))
myfile=open('test','w')
myfile.writelines(mylist1)

即使代码有效,我想知道是否有更好,更有效的方法?是否可以仅通过行号读取文件?


问题答案:

您没有什么可以改善的。但是您必须将所有行都写入 一个新文件 ,无论已更改还是未更改。较小的改进将是:

  • 使用该with语句;
  • 避免将行存储在列表中;
  • 子句中lines不带格式书写else(如果适用)。

应用以上所有内容:

import shutil
with open('test') as old, open('newtest', 'w') as new:
    for line in old:
        if line.rsplit('|', 1)[-1].strip() == 'number3':
            new.write('this is replacement|number7\n')
        else:
            new.write(line)
shutil.move('newtest', 'test')


 类似资料:
  • 使用 electron 的一大好处是可以访问用户的文件系统。这使你可以读取和写入本地系统上的文件。为了避免 Chromium 的限制以及对应用程序内部文件的改写,请确保使用 electron 的 API,特别是 app.getPath(name) 函数。这个帮助函数可以使你获得指向系统目录的文件路径,如用户的桌面、系统临时文件 等等。 使用案例 假设我们想为我们的应用程序提供本地的数据库存储。在这

  • 读写文件是最常见的 IO 操作。通常,我们使用 input 从控制台读取输入,使用 print 将内容输出到控制台。实际上,我们也经常从文件读取输入,将内容写到文件。 读文件 在 Python 中,读文件主要分为三个步骤: 打开文件 读取内容 关闭文件 一般使用形式如下: try: f = open('/path/to/file', 'r') # 打开文件 data = f.

  • 本文向大家介绍C#读写文本文件的方法,包括了C#读写文本文件的方法的使用技巧和注意事项,需要的朋友参考一下 本文实例讲述了C#读写文本文件的方法。分享给大家供大家参考。具体分析如下: System.IO命名空间中的类为托管应用程序提供文件以及其他形式的输入输出。托管i/o的基本构件是流,而流是字节导向的数据的抽象表示。流通过System.IO.Stream类表示. System.IO.FileSt

  • 问题 你需要读写各种不同编码的文本数据,比如ASCII,UTF-8或UTF-16编码等。 解决方案 使用带有 rt 模式的 open() 函数读取文本文件。如下所示: # Read the entire file as a single string with open('somefile.txt', 'rt') as f: data = f.read() # Iterate over

  • 主要内容:C++ >>和<<读写文本文件前面章节中,已经给大家介绍了文件流对象如何调用 open() 方法打开文件,并且在读写(又称 I/O )文件操作结束后,应调用 close() 方法关闭先前打开的文件。那么,如何实现对文件内容的读写呢?接下来就对此问题做详细的讲解。 在讲解具体读写文件的方法之前,读者首先要搞清楚的是,对文件的读/写操作又可以细分为 2 类,分别是以文本形式读写文件和以二进制形式读写文件。 1) 我们知道,文件中存