相关疑难解决方法(0)

如何修改文本文件?

我正在使用Python,并希望在不删除或复制文件的情况下将字符串插入文本文件中.我怎样才能做到这一点?

python text file

164
推荐指数
6
解决办法
35万
查看次数

在文本文件的指定位置插入行

我有一个文本文件,如下所示:

blah blah
foo1 bar1
foo1 bar2
foo1 bar3
foo2 bar4
foo2 bar5
blah blah
Run Code Online (Sandbox Code Playgroud)

现在我想'foo bar''foo1 bar3'和之间插入'foo2 bar4'.

我就这样做了:

import shutil

txt = '1.txt'
tmptxt = '1.txt.tmp'

with open(tmptxt, 'w') as outfile:
    with open(txt, 'r') as infile:
        flag = 0
        for line in infile:
            if not line.startswith('foo1') and flag == 0:
                outfile.write(line)
                continue
            if line.startswith('foo1') and flag == 0:
                flag = 1
                outfile.write(line)
                continue
            if line.startswith('foo1') and flag == 1:
                outfile.write(line)
                continue
            if …
Run Code Online (Sandbox Code Playgroud)

python text insert

31
推荐指数
3
解决办法
5万
查看次数

从文本文件中删除一行

如何使用删除文本文件中的特定行 readlines()

喜欢:

f_open = open("textfile.txt", "r")
lines = f_open.readlines()
Run Code Online (Sandbox Code Playgroud)

你如何使用它lines来选择一行textfile.txt并删除它?

对不起,如果它没有意义.

python text file line readlines

0
推荐指数
1
解决办法
1万
查看次数

标签 统计

python ×3

text ×3

file ×2

insert ×1

line ×1

readlines ×1