在txt文件中sort -u
就像这样
projections.txt
如何更改字符串" true"用"假" (删除)某一行。 例如,如果我输入0002,如何在第二行中更改。 我尝试过类似的东西,但它没有用......
0001|AA|17.12.2017.|20:30|21:00|ponedeljak|For a few dolars more|150|true
0002|BB|19.12.2017.|19:30|21:15|sreda|March on the Drina|300|true
0003|GG|20.12.2017.|18:00|19:00|cetvrtak|A fistful of Dolars|500|true
0004|GG|21.12.2017.|21:15|00:00|petak|The Good, the Bad and the Ugly|350|true
答案 0 :(得分:1)
你的尝试毫无意义。当您修改线条时,修改将丢失。
以读/写方式编写文本文件无法正常工作。在文件中的某处写false
也无法正常工作......
我的建议:
csv
模块来处理拆分import csv
def delete_projection():
with open('projections.txt') as projections:
#projections = open('users.txt', 'r').readlines()
delete = input("Input projection code you want to delete: ")
contents = []
cr = csv.reader(projections,delimiter="|")
for row in cr:
if delete == row[0]:
row[8]="false"
contents.append(row)
with open('projections.txt', 'w',newline="") as projections:
cw = csv.writer(projections,delimiter="|")
cw.writerows(contents)
答案 1 :(得分:0)
你在这里做的事情对我来说似乎是对的,但你只是修改了内存中加载的文件的内容,而不是磁盘上的文件。
您需要将每一行写入一个新文件,因为您是来自projection.txt的处理行 类似的东西:
with open('projections.txt') as projections:
with open('projections-new.txt') as projections_new:
delete = input("Input projection code you want to delete: ")
for i in projections:
projection = i.strip("\n").split("|")
if delete == projection[0]:
projection[8]="false"
projections_new.write("|".join(projection) + "\n")
答案 2 :(得分:0)
您可以使用re
:
import re
s = """
0001|AA|17.12.2017.|20:30|21:00|ponedeljak|For a few dolars more|150|true
0002|BB|19.12.2017.|19:30|21:15|sreda|March on the Drina|300|true
0003|GG|20.12.2017.|18:00|19:00|cetvrtak|A fistful of Dolars|500|true
0004|GG|21.12.2017.|21:15|00:00|petak|The Good, the Bad and the Ugly|350|true
"""
vals = re.findall('(?<=\n)\d+(?=\|)|(?<=^)\d+(?=\|)', s)
statements = re.findall('true|false', s)
new_s = re.sub('true|false', '{}', s)
to_change = '0002'
s = new_s.format(*[('true' if a == 'false' else 'false') if b == to_change else a for a, b in zip(statements, vals)])
输出:
0001|AA|17.12.2017.|20:30|21:00|ponedeljak|For a few dolars more|150|true
0002|BB|19.12.2017.|19:30|21:15|sreda|March on the Drina|300|false
0003|GG|20.12.2017.|18:00|19:00|cetvrtak|A fistful of Dolars|500|true
0004|GG|21.12.2017.|21:15|00:00|petak|The Good, the Bad and the Ugly|350|true