对 txt 文件中的字符串行进行排序,然后用排序后的行覆盖它
Sorting the string lines in a txt file and then overwriting it with the sorted lines
基本上我有一个这样的文件:
hi
my
name
is
我希望它是(按字母顺序排序):
hi
is
my
name
我下面的代码将 txt 文件中的行存储到一个列表中,然后对其进行排序。它可以满足我的要求,但是...:[=13=]
with open ("3ex.txt","r") as f:
new = []
for line in f:
stripped = line.strip("\n")
new.append(stripped)
new.sort() #sorts by letter
print(new)
with open ("3ex.txt","w") as file:
for k in new:
file.write(file"[k]\n")
它不会覆盖它。
我尝试先读取文件然后写入文件。但我一直收到错误。
是的,我知道这样做很糟糕,但这就是我要求的。
从 with 语句中定义 new
列表。并更正 file.write
参数。
这是更正后的代码
new = []
with open ("3ex.txt","r") as f:
for line in f:
stripped = line.strip("\n")
new.append(stripped)
new.sort() #sorts by letter
with open ("3ex.txt","w") as file:
for k in new:
file.write(k + "\n")
基本上我有一个这样的文件:
hi
my
name
is
我希望它是(按字母顺序排序):
hi
is
my
name
我下面的代码将 txt 文件中的行存储到一个列表中,然后对其进行排序。它可以满足我的要求,但是...:[=13=]
with open ("3ex.txt","r") as f:
new = []
for line in f:
stripped = line.strip("\n")
new.append(stripped)
new.sort() #sorts by letter
print(new)
with open ("3ex.txt","w") as file:
for k in new:
file.write(file"[k]\n")
它不会覆盖它。 我尝试先读取文件然后写入文件。但我一直收到错误。
是的,我知道这样做很糟糕,但这就是我要求的。
从 with 语句中定义 new
列表。并更正 file.write
参数。
这是更正后的代码
new = []
with open ("3ex.txt","r") as f:
for line in f:
stripped = line.strip("\n")
new.append(stripped)
new.sort() #sorts by letter
with open ("3ex.txt","w") as file:
for k in new:
file.write(k + "\n")