0

I want to replace a part of text in a file text with python. My part of text to add is stored with a list as you can see with "a list". I detect the part of the text with a counter that works well, my problem seems to be due to my part of ".write" which is defined in a loop with : "fichier_write.write("%.4\n" %a[:][i]) "

#The list I have to add in my file text
a = ['"A01.tiff", "B01.tiff"',
'"A02.tiff","B02.tiff"',
'"A03.tiff","B03.tiff"',
'"A04.tiff","B04.tiff"']

#The format expected is : (i have to suppress " ' " and " [ ] "
"A01.tiff", "B01.tiff",
"A02.tiff","B02.tiff",
"A03.tiff","B03.tiff",
"A04.tiff","B04.tiff"


fichier = open('original.txt',"r")
nb_ligne = 0
chaine = 'image_list ='
for ligne in fichier:
    nb_ligne += 1
    if chaine in ligne:
        break
fichier.close()

#I try to modify my file text with :

fichier_read = open('original.txt',"r")  
fichier_write = open('modified.txt',"w")  

compteur=0.
for ligne in fichier_read:
  compteur=compteur+1
  if compteur != nb_ligne :
    fichier_write.write(ligne)
  else :
    fichier_write.write('image_list = \n')
    for i in range(len(a)):
        fichier_write.write("%.4\n" %a[:][i])  
    break


fichier_write.close()  
fichier_read.close()  

1 Answer 1

1

%a[:][i] is an array. You are likely looking for %a[i]. The format also has a slight error in that it should be
fichier_write.write("%.4s\n" %a[i])
Notice the s at the end for string.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for help but i have still an error : "unsupported format character ' " ...
Is this python 2 or 3? Also worth trying %(a[i])
it must be the 2.7.6 i think
Didn't realize these were strings, you'll need fichier_write.write("%.4s\n" %a[i]) to get the first 4 characters. Note this includes the quotation mark

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.