Python Forum
Adding a new line with content
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Adding a new line with content
#1
Hello, I'm having a (little) issue by adding a new line. The newline is added before the line I want.

See my code

for fichier in os.listdir("result/"):
    if not fnmatch.fnmatch(fichier, 'file_0.txt'):
        # print(fichier)
        with fileinput.input(["result/"+fichier], inplace=1) as file_X :
            print("---------------------------------")
            for line in file_X:
                line = line.strip('\n')
                if line.startswith("/54/"):
                    split = line.split("/")
                    num = split[2]
                    for pj in pjCSV:
                        if num in pj:
                            ...
                            sys.stderr.write(new_name + "\r\n")
                if line.startswith('/22/'):
                    sys.stderr.write(line)
                    print("coucou") # this is added before the line starting with /22/, I want after
                print (line.rstrip('\n')) # 

            break

Solution :

for fichier in os.listdir("result/"):
    if not fnmatch.fnmatch(fichier, 'file_0.txt'):
        with fileinput.input(["result/"+fichier], inplace=1) as file_X :
            # file_X.write('\r\ncoucou')
            print("---------------------------------")
            for line in file_X:
                line = line.strip('\n')
                if line.startswith("/54/"):
                    split = line.split("/")
                    num = split[2]
                    # print(num)
                    for pj in pjCSV:
                        if num in pj:
                            ...
                            sys.stderr.write(new_name + "\r\n")
                if line.startswith('/22/'):
                    print(line.replace(line, line+"\r\n"))
                    continue
                print (line.rstrip('\n')) # ecriture de toutes les lignes

            break
Reply
#2
I don't understand print(line.replace(line, line+"\r\n")). Why not simply print(line + "\r\n")? Apart from that, the issue is solved isn't it?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Adding markers to Folium map only adding last element. tantony 0 2,119 Oct-16-2019, 03:28 PM
Last Post: tantony
  Adding a line number to an lxml Element vindy 0 3,337 Mar-08-2019, 08:34 PM
Last Post: vindy
  Adding new line in a one line txt file. Mady 7 3,587 Nov-21-2018, 01:04 PM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020