Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在某些特定行的末尾添加文本_Python - Fatal编程技术网

Python 如何在某些特定行的末尾添加文本

Python 如何在某些特定行的末尾添加文本,python,Python,我有一个文件,其中包含: /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/”

我有一个文件,其中包含:

    /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

快速简便的操作方法:

    # 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)

你试过什么?无论是否使用Python,这都是一项非常直接的任务。你的问题在哪里?对我来说,它似乎与Ubuntu不太相关。大多数其他操作系统也可以有文件。我需要一个命令,它将添加一个标签,如0,1,2,3。。。根据文件夹名称在行的末尾。不同的文件夹图像将具有不同的标签。但相同的文件夹图像将有相同的标签。我正在尝试这个网站谢谢你,但我找到了我的答案。。。
    # 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)