2017-09-05 12 views
-1

次のコードが実行されたとき、特に最後の 'else'条件が発生した場合、このエラーが発生します:OSError:[Errno 22]無効な引数: 'My Name \ n- Groups.txt 'ファイル名の末尾にある nを削除する方法

ファイル名に「\ 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

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

をので、あなたのコードでは、次のような変更を行うことができます、 '') – MedAli

答えて

2

このような何かを行うことができます:あなたはstr.replace( '\ n' を使用することができます

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