简体   繁体   中英

How to save each loop of a python function to a separate file?

I have a question regarding a small Python program I would like to finish. I learned about coding, but this is my first real program.

With this program I want to combine 2 textfiles and insert a privnote link in between of those 2 files. In the end I want to save this combined file to a new output file. This function should be looped for a pre defined amount of times and each loop should be saved in a separate file:

This is my code:

import pyPrivnote as pn
import sys

def Text():
    Teil_1  = open("Teil_1.txt", "r")
    Content_1 = Teil_1.read()
    print(Content_1)

    note_link = pn.create_note("Data")
    print(note_link)

    Teil_2  = open("Teil_2.txt", "r")
    Content_2 = Teil_2.read()
    print(Content_2)

Above part works. Next part is where I struggle.

i = 0 + 1
while i <= 3:
    filename = "C:\\Users\\Python\\Datei%d.txt" % i
    f = open(filename, "r")
    Text()
    f.close()

How can I save each loop output of the Text() function to a new file?

I would like to save it the output to the relative path /output/ and the files should have the name "file01, file02...".

I searched for several hours now, but I don´t find an answer to this problem.

Thanks in advance for your help!

Pass the file to Text() :

def Text(out_file):
    Teil_1  = open("Teil_1.txt", "r")
    Content_1 = Teil_1.read()
    out_file.write(Content_1)
    Teil_1.close()

    note_link = pn.create_note("Data")
    out_file.write(note_link)

    Teil_2  = open("Teil_2.txt", "r")
    Content_2 = Teil_2.read()
    out_file.write(Content_2)
    Teil_2.close()

And:

i = 1
while i <= 3:
    filename = "C:\\Users\\Python\\Datei%d.txt" % i
    i += 1
    f = open(filename, "rw")
    Text(f)
    f.close()

But inside the loop you are opening 2 files. There are easier ways to achieve this if you want to write the content of these files in one single file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM