![](/img/trans.png)
[英]How to replace the first specific special character in each line by not touching the rest of that word in each of the line of a text file in python
[英]How do check for a specific character at the end of each line in a text file
我编写了一个脚本,将给定字符附加到文本文件的每一行(我在 IP 地址的末尾添加了','
,每行一个)
我想防止意外多次运行脚本并将多个相同的字符添加到脚本的末尾。 即添加一个,
是我想要的,不小心添加了十个,
这很烦人,我需要撤消我所做的事情。
我正在尝试更新代码以识别一行中的最后一个字符是否与尝试添加的字符相同,如果是,则不要添加它。
此代码将char
添加到每行的末尾。
file = 'test.txt' # file to append text to, keep the ''
char = ','
newf=""
with open(file,'r') as f:
for line in f:
newf+=line.strip()+ char + '\n'
f.close()
with open(file,'w') as f:
f.write(newf)
f = open("test.txt", "r")
check = ","
而且我编写了这段代码来检查每行的最后一个字符是什么,它为每一行成功返回一个','
。 我不知道如果char
和check
是相同的值,如何组合,而不是 append 任何东西。
f = open("test.txt", "r")
check = ","
for line in f:
l = line.strip()
if l[-1:].isascii():
check = l[-1:]
else:
check = 0
print(check)
f.close()
使用endswith()
function 检查它是否已经以,
结尾。
check = ","
newf = ""
with open(file) as f:
for line in f:
line = line.strip()
if not line.endswith(check):
line += check
newf += line + "\n"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.