![](/img/trans.png)
[英]How to search and read a text file in a specific folder faster using python
[英]Read and search text file in Python?
我需要編寫一個Python腳本,該腳本讀取一個純文本文件,搜索一個字符串,然后重寫為一個新的文本文件。
我有這個(示例)腳本:
import re
read = open("file.txt", "r")
data = file.read()
print data
newfile = open("newfile.txt", "w")
for line in read:
if re.match("(.*)dst="+str_var"(.*)", line):
print newfile, line,
file.close()
有沒有更簡單或更正確的方法? (我對Python幾乎一無所知。這段代碼是從我在教程,谷歌等中找到的東西派生的。)
謝謝!
這可能會解決問題
read_file = open("file.txt", "r")
data = read_file.read()
read_file.close()
file_content = re.sub("\d+", "", data)
word = your_word
if word in file_content:
newfile = open("newfile.txt", "w")
print >> newfile, word
newfile.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.