这是一个示例文本文件
the bird flew
the dog barked
the cat meowed
Run Code Online (Sandbox Code Playgroud)
这是我的代码,以找到我想删除的短语的行号
phrase = 'the dog barked'
with open(filename) as myFile:
for num, line in enumerate(myFile, 1):
if phrase in line:
print 'found at line:', num
Run Code Online (Sandbox Code Playgroud)
我可以添加什么来删除我尝试过的行号(num)
lines = myFile.readlines()
del line[num]
Run Code Online (Sandbox Code Playgroud)
但这不起作用我应该如何处理这个?
首先感谢帮助我移动文件和帮助我使用tcl脚本.
小疑问我有python代码..如下所示..
import os
import shutil
data =" set filelid [open \"C:/Sanity_Automation/Work_Project/Output/smokeTestResult\" w+] \n\
puts $filelid \n\
close $filelid \n"
path = "C:\\Sanity_Automation\\RouterTester900SystemTest"
if os.path.exists(path):
shutil.rmtree('C:\\Sanity_Automation\\RouterTester900SystemTest\\')
path = "C:\\Program Files (x86)"
if os.path.exists(path):
src= "C:\\Program Files (x86)\\abc\\xyz\\QuickTest\\Scripts\\RouterTester900\\Diagnostic\\RouterTester900SystemTest"
else:
src= "C:\\Program Files\\abc\\xyz\\QuickTest\\Scripts\\RouterTester900\\Diagnostic\\RouterTester900SystemTest"
dest = "C:\\Sanity_Automation\\RouterTester900SystemTest\\"
shutil.copytree(src, dest)
log = open('C:\\Sanity_Automation\\RouterTester900SystemTest\\RouterTester900SystemTest.app.tcl','r+')
log_read=log.readlines()
x="CloseAllOutputFile"
with open('C:\\Sanity_Automation\\RouterTester900SystemTest\\RouterTester900SystemTest.app.tcl', 'a+') as fout:
for line in log_read:
if x in line:
fout.seek(0,1)
fout.write("\n")
fout.write(data)
Run Code Online (Sandbox Code Playgroud)
此代码用于将文件从一个位置复制到另一个位置,在特定文件中搜索关键字并将数据写入文件正在运行...
我的疑问是每当我写的..它写到文件末尾而不是当前位置...
示例:说..我将文件从程序文件复制到sanity文件夹,并在其中一个复制文件中搜索单词"CloseAllOutputFile".当找到单词时,它应该在该位置插入文本而不是文件末尾.
我有一个带有以下几行的文本文件Thailand_Rectangle2_National Parks.txt。
1
2
3
4
5
dy 0.5965
7
Run Code Online (Sandbox Code Playgroud)
现在,我想删除此文本文件中的第六行。
为此,我正在使用以下python代码。
f = open("C:/Users/Sreeraj/Desktop/Thailand_Rectangle2_National Parks.txt","r")
lines = f.readlines()
Run Code Online (Sandbox Code Playgroud)
因此,我将此文本文件的所有行都保存在“ lines”中。
line6 = lines[5]
t = line6[:2]
f.close()
Run Code Online (Sandbox Code Playgroud)
所以,现在,我有't'=“ dy”。现在,
if t == "dy":
f = open("C:/Users/Sreeraj/Desktop/Thailand_Rectangle2_National Parks.txt","w")
for line in lines:
if lines[5] != line6:
f.write(line)
f.close()
Run Code Online (Sandbox Code Playgroud)
因此,如果满足条件't'=“ dy”,那么我将打开该文本文件进行写入,并打印除line6以外的所有行(这意味着从该文本文件中删除了line6)。
不幸的是,我在文本文件中得到的行是空白,这意味着没有行被打印为输出。
但是,我希望文本文件中的行如下所示。
1
2
3
4
5
7
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个问题?
我只想使用Python编程来解决此问题;因为这是一项主要工作的小任务。
可能的重复:
删除文件中的特定行(python)
我需要从文件 f= 中删除包含数字“2”的行
2 3
5 6
7 2
4 5
Run Code Online (Sandbox Code Playgroud) 如何使用删除文本文件中的特定行 readlines()
喜欢:
f_open = open("textfile.txt", "r")
lines = f_open.readlines()
Run Code Online (Sandbox Code Playgroud)
你如何使用它lines来选择一行textfile.txt并删除它?
对不起,如果它没有意义.