我有一个文件,其中包含:
/home/hedgehog/image_0037.jpg
/home/hedgehog/image_0048.jpg
/home/hedgehog/image_0039.jpg
/home/brain/image_0053.jpg
/home/brain/image_0097.jpg
/home/brain/image_0004.jpg
我想在包含“ / hedgehog /”的行末添加0,并想在包含“ / brain /”的行末添加1,如下所示:
/home/hedgehog/image_0037.jpg 0
/home/hedgehog/image_0048.jpg 0
/home/hedgehog/image_0039.jpg 0
/home/brain/image_0053.jpg 1
/home/brain/image_0097.jpg 1
/home/brain/image_0004.jpg 1
答案 0 :(得分:0)
Value
答案 1 :(得分:0)
快速简便的方法:
# new data to be written
new_data = ""
# open text file
with open ("input.txt", "r+") as in_file:
# loop each line
for line in in_file:
# remove newline character
line = line.strip("\n\r")
if "hedgehog" in line:
line+=" 0"
if "brain" in line:
line+=" 1"
# create the new version and add it to the new file data
new_data+=line+"\n"
# write to the file
with open ("input.txt", "w+") as out_file:
out_file.write(new_data)