Làm cách nào để tìm kiếm và thay thế văn bản trong một tệp bằng Python 3?
Đây là mã của tôi:
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 Enter to exit...' ]
Tệp đầu vào:
hi this is abcd hi this is abcd
This is dummy text file.
This is how search and replace works abcd
Khi tôi tìm kiếm và thay thế 'Ram' bằng 'ABCD' trong tệp đầu vào ở trên, nó hoạt động như một sự quyến rũ. Nhưng khi tôi thực hiện nó ngược lại, tức là thay thế 'ABCD' bằng 'Ram', một số ký tự rác bị bỏ lại ở cuối.
Thay thế 'ABCD' bằng 'Ram'
hi this is ram hi this is ram
This is dummy text file.
This is how search and replace works rambcd
PPPERY
3.62220 Huy hiệu vàng31 Huy hiệu bạc44 Huy hiệu đồng20 gold badges31 silver badges44 bronze badges
hỏi ngày 17 tháng 6 năm 2013 lúc 5:24Jun 17, 2013 at 5:24
4
Như Michaelb958 đã chỉ ra, bạn không thể thay thế tại chỗ bằng dữ liệu có độ dài khác vì điều này sẽ khiến phần còn lại của các phần không đúng chỗ. Tôi không đồng ý với các áp phích khác cho thấy bạn đọc từ một tệp này và ghi sang một tệp khác. Thay vào đó, tôi sẽ đọc tệp vào bộ nhớ, sửa dữ liệu và sau đó viết nó ra cùng một tệp trong một bước riêng biệt.
# Read in the file
with open['file.txt', 'r'] as file :
filedata = file.read[]
# Replace the target string
filedata = filedata.replace['ram', 'abcd']
# Write the file out again
with open['file.txt', 'w'] as file:
file.write[filedata]
Trừ khi bạn có một tệp lớn để hoạt động quá lớn để tải vào bộ nhớ trong một lần hoặc bạn lo ngại về việc mất dữ liệu tiềm năng nếu quá trình bị gián đoạn trong bước thứ hai mà bạn viết dữ liệu vào tệp.
Đã trả lời ngày 17 tháng 6 năm 2013 lúc 6:29Jun 17, 2013 at 6:29
Jack Aidleyjack AidleyJack Aidley
Phim thương hiệu vàng 18,9K742 Huy hiệu bạc70 Hàng đồng7 gold badges42 silver badges70 bronze badges
24
hi this is ram hi this is ram
This is dummy text file.
This is how search and replace works rambcd
6 đã hỗ trợ chỉnh sửa tại chỗ. Nó chuyển hướng hi this is ram hi this is ram
This is dummy text file.
This is how search and replace works rambcd
7 đến tệp trong trường hợp này:#!/usr/bin/env python3
import fileinput
with fileinput.FileInput[filename, inplace=True, backup='.bak'] as file:
for line in file:
print[line.replace[text_to_search, replacement_text], end='']
Jacktose
6697 Huy hiệu bạc21 Huy hiệu Đồng7 silver badges21 bronze badges
Đã trả lời ngày 15 tháng 12 năm 2013 lúc 10:47Dec 15, 2013 at 10:47
JFSJFSjfs
386K184 Huy hiệu vàng950 Huy hiệu bạc1626 Huy hiệu Đồng184 gold badges950 silver badges1626 bronze badges
25
Như Jack Aidley đã đăng và J.F. Sebastian đã chỉ ra, mã này sẽ không hoạt động:
# Read in the file
filedata = None
with file = open['file.txt', 'r'] :
filedata = file.read[]
# Replace the target string
filedata.replace['ram', 'abcd']
# Write the file out again
with file = open['file.txt', 'w'] :
file.write[filedata]`
Nhưng mã này sẽ hoạt động [tôi đã thử nghiệm nó]:
f = open[filein,'r']
filedata = f.read[]
f.close[]
newdata = filedata.replace["old data","new data"]
f = open[fileout,'w']
f.write[newdata]
f.close[]
Sử dụng phương thức này, Filein và FileOut có thể là cùng một tệp, bởi vì Python 3.3 sẽ ghi đè lên tệp khi mở để ghi.
Đã trả lời ngày 5 tháng 4 năm 2014 lúc 5:19Apr 5, 2014 at 5:19
NeamerjellneamerjellNeamerjell
8176 Huy hiệu bạc7 Huy hiệu đồng6 silver badges7 bronze badges
4
Bạn có thể thực hiện thay thế như thế này
f1 = open['file1.txt', 'r']
f2 = open['file2.txt', 'w']
for line in f1:
f2.write[line.replace['old_text', 'new_text']]
f1.close[]
f2.close[]
Đã trả lời ngày 17 tháng 6 năm 2013 lúc 5:32Jun 17, 2013 at 5:32
JayramjayramJayram
18.3k6 Huy hiệu vàng49 Huy hiệu bạc68 Huy hiệu Đồng6 gold badges49 silver badges68 bronze badges
0
Bạn cũng có thể sử dụng
hi this is ram hi this is ram
This is dummy text file.
This is how search and replace works rambcd
8.from pathlib2 import Path
path = Path[file_to_search]
text = path.read_text[]
text = text.replace[text_to_search, replacement_text]
path.write_text[text]
Georgy
11.1k7 Huy hiệu vàng62 Huy hiệu bạc70 Huy hiệu đồng7 gold badges62 silver badges70 bronze badges
Đã trả lời ngày 8 tháng 2 năm 2019 lúc 2:24Feb 8, 2019 at 2:24
1
[PIP Cài đặt Python-Util]
from pyutil import filereplace
filereplace["somefile.txt","abcd","ram"]
Sẽ thay thế tất cả các sự cố của "ABCD" bằng "RAM". Chức năng cũng hỗ trợ Regex bằng cách chỉ định
hi this is ram hi this is ram
This is dummy text file.
This is how search and replace works rambcd
9The function also supports regex by specifying
hi this is ram hi this is ram
This is dummy text file.
This is how search and replace works rambcd
9hi this is abcd hi this is abcd
This is dummy text file.
This is how search and replace works abcd
0Tuyên bố miễn trừ trách nhiệm: Tôi là tác giả [//github.com/misterl2/python-util]
Đã trả lời ngày 23 tháng 8 năm 2019 lúc 13:43Aug 23, 2019 at 13:43
MisterL2MisterL2MisterL2
1613 Huy hiệu bạc6 Huy hiệu đồng3 silver badges6 bronze badges
5
Câu trả lời này làm việc cho tôi. Mở tệp ở chế độ đọc. Đọc tệp ở định dạng chuỗi. Thay thế văn bản như dự định. Đóng tệp. Một lần nữa mở tệp trong chế độ ghi. Cuối cùng, viết văn bản thay thế vào cùng một tệp.
hi this is abcd hi this is abcd
This is dummy text file.
This is how search and replace works abcd
1Đã trả lời ngày 16 tháng 4 năm 2021 lúc 17:40Apr 16, 2021 at 17:40
SanzvsanzvSanzv
Phù hiệu bằng đồng 911 Huy hiệu đồng1 silver badge2 bronze badges
Câu trả lời muộn, nhưng đây là những gì tôi sử dụng để tìm và thay thế bên trong tệp văn bản:
hi this is abcd hi this is abcd
This is dummy text file.
This is how search and replace works abcd
2THỬ NGHIỆM
Đã trả lời ngày 22 tháng 8 năm 2020 lúc 3:35Aug 22, 2020 at 3:35
Pedro lobitopedro lobitoPedro Lobito
89.5K30 Huy hiệu vàng239 Huy hiệu bạc259 Huy hiệu Đồng30 gold badges239 silver badges259 bronze badges
2
Với một khối duy nhất, bạn có thể tìm kiếm và thay thế văn bản của mình:
hi this is abcd hi this is abcd
This is dummy text file.
This is how search and replace works abcd
3Đã trả lời ngày 14 tháng 6 năm 2019 lúc 13:00Jun 14, 2019 at 13:00
1
Vấn đề của bạn bắt nguồn từ việc đọc và ghi vào cùng một tệp. Thay vì mở
# Read in the file
with open['file.txt', 'r'] as file :
filedata = file.read[]
# Replace the target string
filedata = filedata.replace['ram', 'abcd']
# Write the file out again
with open['file.txt', 'w'] as file:
file.write[filedata]
0 để viết, hãy mở một tệp tạm thời thực tế và sau đó sau khi bạn hoàn thành và đã đóng # Read in the file
with open['file.txt', 'r'] as file :
filedata = file.read[]
# Replace the target string
filedata = filedata.replace['ram', 'abcd']
# Write the file out again
with open['file.txt', 'w'] as file:
file.write[filedata]
1, sử dụng # Read in the file
with open['file.txt', 'r'] as file :
filedata = file.read[]
# Replace the target string
filedata = filedata.replace['ram', 'abcd']
# Write the file out again
with open['file.txt', 'w'] as file:
file.write[filedata]
2 để di chuyển tệp mới qua # Read in the file
with open['file.txt', 'r'] as file :
filedata = file.read[]
# Replace the target string
filedata = filedata.replace['ram', 'abcd']
# Write the file out again
with open['file.txt', 'w'] as file:
file.write[filedata]
0.Đã trả lời ngày 17 tháng 6 năm 2013 lúc 5:43Jun 17, 2013 at 5:43
icktoofayicktoofayicktoofay
Huy hiệu vàng 124K2020 gold badges244 silver badges229 bronze badges
1
Biến thể của tôi, một từ tại một thời điểm trên toàn bộ tệp.
Tôi đọc nó vào bộ nhớ.
hi this is abcd hi this is abcd
This is dummy text file.
This is how search and replace works abcd
4Đã trả lời ngày 15 tháng 12 năm 2013 lúc 10:19Dec 15, 2013 at 10:19
LipilipiLiPi
1791 Huy hiệu bạc5 Huy hiệu đồng1 silver badge5 bronze badges
Tôi đã thử cái này và sử dụng các bản đọc lại thay vì đọc
hi this is abcd hi this is abcd
This is dummy text file.
This is how search and replace works abcd
5Đã trả lời ngày 2 tháng 3 năm 2021 lúc 10:44Mar 2, 2021 at 10:44
Tôi đã làm điều này:
hi this is abcd hi this is abcd
This is dummy text file.
This is how search and replace works abcd
6Đã trả lời ngày 16 tháng 2 năm 2017 lúc 21:26Feb 16, 2017 at 21:26
1
hi this is abcd hi this is abcd
This is dummy text file.
This is how search and replace works abcd
7Đã trả lời ngày 23 tháng 1 năm 2018 lúc 18:45Jan 23, 2018 at 18:45
1
Bên cạnh các câu trả lời đã được đề cập, đây là một lời giải thích về lý do tại sao bạn có một số ký tự ngẫu nhiên ở cuối: bạn đang mở tệp ở chế độ
# Read in the file
with open['file.txt', 'r'] as file :
filedata = file.read[]
# Replace the target string
filedata = filedata.replace['ram', 'abcd']
# Write the file out again
with open['file.txt', 'w'] as file:
file.write[filedata]
4, không phải chế độ # Read in the file
with open['file.txt', 'r'] as file :
filedata = file.read[]
# Replace the target string
filedata = filedata.replace['ram', 'abcd']
# Write the file out again
with open['file.txt', 'w'] as file:
file.write[filedata]
5. Sự khác biệt chính là chế độ # Read in the file
with open['file.txt', 'r'] as file :
filedata = file.read[]
# Replace the target string
filedata = filedata.replace['ram', 'abcd']
# Write the file out again
with open['file.txt', 'w'] as file:
file.write[filedata]
5 xóa nội dung của tệp ngay khi bạn mở nó, trong khi # Read in the file
with open['file.txt', 'r'] as file :
filedata = file.read[]
# Replace the target string
filedata = filedata.replace['ram', 'abcd']
# Write the file out again
with open['file.txt', 'w'] as file:
file.write[filedata]
4 thì không. Điều này có nghĩa là nếu nội dung tệp của bạn là "123456789" và bạn viết "www" cho nó, bạn sẽ nhận được "www456789". Nó ghi đè lên các ký tự với đầu vào mới, nhưng để lại bất kỳ đầu vào còn lại. Bạn có thể xóa một phần của nội dung tệp bằng cách sử dụng # Read in the file
with open['file.txt', 'r'] as file :
filedata = file.read[]
# Replace the target string
filedata = filedata.replace['ram', 'abcd']
# Write the file out again
with open['file.txt', 'w'] as file:
file.write[filedata]
8, nhưng có lẽ bạn nên lưu nội dung tệp được cập nhật tốt nhất trước một chuỗi trước, sau đó thực hiện # Read in the file
with open['file.txt', 'r'] as file :
filedata = file.read[]
# Replace the target string
filedata = filedata.replace['ram', 'abcd']
# Write the file out again
with open['file.txt', 'w'] as file:
file.write[filedata]
9 và viết tất cả cùng một lúc. Hoặc bạn có thể sử dụng thư viện của tôi: DYou are opening the file in
# Read in the file
with open['file.txt', 'r'] as file :
filedata = file.read[]
# Replace the target string
filedata = filedata.replace['ram', 'abcd']
# Write the file out again
with open['file.txt', 'w'] as file:
file.write[filedata]
4 mode, not # Read in the file
with open['file.txt', 'r'] as file :
filedata = file.read[]
# Replace the target string
filedata = filedata.replace['ram', 'abcd']
# Write the file out again
with open['file.txt', 'w'] as file:
file.write[filedata]
5 mode. The key difference is that # Read in the file
with open['file.txt', 'r'] as file :
filedata = file.read[]
# Replace the target string
filedata = filedata.replace['ram', 'abcd']
# Write the file out again
with open['file.txt', 'w'] as file:
file.write[filedata]
5 mode clears the contents of the file as soon as you open it, whereas # Read in the file
with open['file.txt', 'r'] as file :
filedata = file.read[]
# Replace the target string
filedata = filedata.replace['ram', 'abcd']
# Write the file out again
with open['file.txt', 'w'] as file:
file.write[filedata]
4 doesn't.This means that if your file content is "123456789" and you write "www" to it, you get "www456789". It overwrites the characters with the new input, but leaves any remaining input untouched.
You can clear a section of the file contents by using
# Read in the file
with open['file.txt', 'r'] as file :
filedata = file.read[]
# Replace the target string
filedata = filedata.replace['ram', 'abcd']
# Write the file out again
with open['file.txt', 'w'] as file:
file.write[filedata]
8, but you are probably best off saving the updated file content to a string first, then doing # Read in the file
with open['file.txt', 'r'] as file :
filedata = file.read[]
# Replace the target string
filedata = filedata.replace['ram', 'abcd']
# Write the file out again
with open['file.txt', 'w'] as file:
file.write[filedata]
9 and writing it all at once.Or you can use my library :D
Đã trả lời ngày 15 tháng 12 năm 2020 lúc 1:18Dec 15, 2020 at 1:18
MisterL2MisterL2MisterL2
1613 Huy hiệu bạc6 Huy hiệu đồng3 silver badges6 bronze badges
Câu trả lời này làm việc cho tôi. Mở tệp ở chế độ đọc. Đọc tệp ở định dạng chuỗi. Thay thế văn bản như dự định. Đóng tệp. Một lần nữa mở tệp trong chế độ ghi. Cuối cùng, viết văn bản thay thế vào cùng một tệp.
hi this is abcd hi this is abcd
This is dummy text file.
This is how search and replace works abcd
8Đã trả lời ngày 26 tháng 2 năm 2021 lúc 13:07Feb 26, 2021 at 13:07
Bạn có thể sử dụng SED hoặc AWK hoặc Grep trong Python [với một số hạn chế]. Đây là một ví dụ rất đơn giản. Nó thay đổi chuối thành Bananatoothpaste trong tệp. Bạn có thể chỉnh sửa và sử dụng nó. .
hi this is abcd hi this is abcd
This is dummy text file.
This is how search and replace works abcd
9Nếu bạn muốn xem kết quả trên tệp được áp dụng trực tiếp: "Nhập" cho Windows/ "Cat" cho Linux:
hi this is ram hi this is ram
This is dummy text file.
This is how search and replace works rambcd
0Đã trả lời ngày 3 tháng 4 lúc 15:27Apr 3 at 15:27
Baris Kurtbaris KurtBARIS KURT
3643 Huy hiệu bạc13 Huy hiệu Đồng3 silver badges13 bronze badges
Sử dụng
#!/usr/bin/env python3
import fileinput
with fileinput.FileInput[filename, inplace=True, backup='.bak'] as file:
for line in file:
print[line.replace[text_to_search, replacement_text], end='']
0, có thể có nhiều quyền kiểm soát hơn đối với quá trình thay thế, chẳng hạn như chia tách từ trên hai dòng, phù hợp nhạy cảm với trường hợp. Hơn nữa, nó trả về số lượng trận đấu có thể được sử dụng để tránh lãng phí tài nguyên nếu không tìm thấy chuỗi.hi this is ram hi this is ram
This is dummy text file.
This is how search and replace works rambcd
1Một số regex:
- Thêm cờ
1, dạng ngắn của#!/usr/bin/env python3 import fileinput with fileinput.FileInput[filename, inplace=True, backup='.bak'] as file: for line in file: print[line.replace[text_to_search, replacement_text], end='']
2, cho trận đấu không nhạy cảm với trường hợp#!/usr/bin/env python3 import fileinput with fileinput.FileInput[filename, inplace=True, backup='.bak'] as file: for line in file: print[line.replace[text_to_search, replacement_text], end='']
- Đối với thay thế đa dòng
3, tùy thuộc vào dữ liệu cũng#!/usr/bin/env python3 import fileinput with fileinput.FileInput[filename, inplace=True, backup='.bak'] as file: for line in file: print[line.replace[text_to_search, replacement_text], end='']
4. Lưu ý rằng trong trường hợp này#!/usr/bin/env python3 import fileinput with fileinput.FileInput[filename, inplace=True, backup='.bak'] as file: for line in file: print[line.replace[text_to_search, replacement_text], end='']
5 phải là một chuỗi thuần túy, không phải là một regex!#!/usr/bin/env python3 import fileinput with fileinput.FileInput[filename, inplace=True, backup='.bak'] as file: for line in file: print[line.replace[text_to_search, replacement_text], end='']
Đã trả lời ngày 6 tháng 8 lúc 22:47Aug 6 at 22:47
LardScardscards
3.2751 Huy hiệu vàng5 Huy hiệu bạc23 Huy hiệu đồng1 gold badge5 silver badges23 bronze badges
Tôi đã sửa đổi bài đăng của Jayram Singh một chút để thay thế mọi trường hợp của một '!' ký tự cho một số mà tôi muốn tăng theo từng trường hợp. Nghĩ rằng nó có thể hữu ích cho một người muốn sửa đổi một nhân vật xảy ra nhiều hơn một lần trên mỗi dòng và muốn lặp lại. Hy vọng điều đó sẽ giúp ai đó. PS- Tôi rất mới trong mã hóa nên xin lỗi nếu bài đăng của tôi không phù hợp theo bất kỳ cách nào, nhưng điều này làm việc cho tôi.
hi this is ram hi this is ram
This is dummy text file.
This is how search and replace works rambcd
2Đã trả lời ngày 24 tháng 9 năm 2017 lúc 16:57Sep 24, 2017 at 16:57
Tôi đã thực hiện điều này như một bài tập của một khóa học: mở tệp, tìm và thay thế chuỗi và ghi vào một tệp mới.
hi this is ram hi this is ram
This is dummy text file.
This is how search and replace works rambcd
3
Ruli
2.48112 Huy hiệu vàng29 Huy hiệu bạc37 Huy hiệu đồng12 gold badges29 silver badges37 bronze badges
Đã trả lời ngày 15 tháng 2 năm 2021 lúc 16:52Feb 15, 2021 at 16:52
hi this is ram hi this is ram
This is dummy text file.
This is how search and replace works rambcd
4Đã trả lời ngày 20 tháng 6 năm 2018 lúc 10:06Jun 20, 2018 at 10:06
Deepak gdeepak gDeepak G
5626 Huy hiệu bạc9 Huy hiệu Đồng6 silver badges9 bronze badges
Như vậy:
hi this is ram hi this is ram
This is dummy text file.
This is how search and replace works rambcd
5Đã trả lời ngày 17 tháng 1 năm 2020 lúc 7:08Jan 17, 2020 at 7:08
2