相关疑难解决方法(0)

如何使用Python搜索和替换文件中的文本?

如何使用Python 3搜索和替换文件中的文本?

这是我的代码:

import os
import sys
import fileinput

print ("Text to search for:")
textToSearch = input( "> " )

print ("Text to replace it with:")
textToReplace = input( "> " )

print ("File to perform Search-Replace on:")
fileToSearch  = input( "> " )
#fileToSearch = 'D:\dummy1.txt'

tempFile = open( fileToSearch, 'r+' )

for line in fileinput.input( fileToSearch ):
    if textToSearch in line :
        print('Match Found')
    else:
        print('Match Not Found!!')
    tempFile.write( line.replace( textToSearch, textToReplace ) )
tempFile.close()


input( '\n\n Press …
Run Code Online (Sandbox Code Playgroud)

python string replace file python-3.x

179
推荐指数
8
解决办法
52万
查看次数

使用Python删除文件中的特定行

假设我有一个充满昵称的文本文件.如何使用Python从此文件中删除特定昵称?

python file input

127
推荐指数
6
解决办法
34万
查看次数

用Python在文件中间插入行?

有没有办法做到这一点?假设我有一个文件列表,其名称如下:

  1. 阿尔弗雷德
  2. 法案
  3. 唐纳德

如何在第x行(在本例中为3)插入第三个名称"Charlie",并自动将所有其他名称下移一行?我见过这样的其他问题,但他们没有得到有用的答案.可以这样做,最好是用方法还是循环?

python

50
推荐指数
6
解决办法
8万
查看次数

在 Python 中替换文件中的文本

我使用以下代码在编辑后使用 FTP 在服务器上上传文件:

import fileinput

file = open('example.php','rb+')

for line in fileinput.input('example.php'):
    if 'Original' in line :
        file.write( line.replace('Original', 'Replacement'))

file.close()    
Run Code Online (Sandbox Code Playgroud)

有一件事,不是替换原来位置的文本,而是代码在末尾添加替换的文本,并且原始位置的文本不变。

此外,它不仅打印出替换的文本,还打印出整行。谁能告诉我如何解决这两个错误?

python file python-3.x python-3.5

3
推荐指数
1
解决办法
5422
查看次数

标签 统计

python ×4

file ×3

python-3.x ×2

input ×1

python-3.5 ×1

replace ×1

string ×1