如何删除文件名末尾的\ n

时间:2017-09-05 09:57:59

标签: python-3.x

当下面的代码运行时,最具体的是最后一个'else'条件,我得到这个错误:OSError:[Errno 22]无效的参数:'My Name \ n-Groups.txt'

我该怎么办才能使'\ n'不包含在文件名中,因为我希望它只是'My Name-Groups.txt'。

def add_child_to_group():
    file = open("Children.txt", 'r')  # open the Children.txt file
    lineList = file.readlines()
    lineList.sort()
    file.close()
    choice1 = choicebox('Choose a child to enter into a group.', 'Add child to a group. ', choices=lineList)
    if choice1 is None:
        print("You cancelled... returning to the main menu.")
        main()
        return
   else:
        file = open("Groups.txt", 'r')
        lineList = [line.strip() for line in file]
        choice2 = choicebox("Which group would you like to add the child to?", "Choose a group.",
                        choices=lineList)
        file.close()
        if choice2 is None:
            print("You cancelled... returning to the main menu.")
            main()
            return
        else:
            if choice1 in open('%s.txt' % choice2).read():
                child_already_in_group(choice1, choice2)
                return
            else:
                file1 = open('%s.txt' % choice2, 'a')
                file1.write(str(choice1))
                print(str(choice1) + "was added to the " + str(choice2) + " group")
                file1.close()
                file2 = open('%s-Groups.txt' % choice1, 'a')
                file2.write(str(choice2))

1 个答案:

答案 0 :(得分:2)

这样的事情可以做到:

>>> st = 'My Name\n-Groups.txt'
>>> st.replace('\n','')
'My Name-Groups.txt'
>>> 

因此,在您的代码中,您可以进行以下更改:

file2 = open(('%s-Groups.txt' % choice1).replace('\n',''), 'a')