-4

I have a txt file from where I want to create new files based on the data which is up to '$'character.

My input file looks like:

string1
string2
string3
$string4
string5
$string6
string7
... (and so on)

My first output file should be:

string1
string2
string3

My second file should be (without "$"):

string4
string5

and so on until it reaches the end of the data in the input file.

So far, I did below code which is only printing the data up to first '$' (first file example above). I don't know how to create a new file based on the print below (first file example) and how to continue the loop to check the rest of the file and to create each file within the range above.

file = open ("test.txt")

# read the file line by line
for lx in file:
    ly = lx.strip() # remove blank rows
    if ly.startswith('$'): # stop the loop when line starts with $
        break
    print(ly)
file.close()```

1 Answer 1

-1

@Ivan, this isn't really a software engineering question. It would be better posted on the StackOverflow site which deals with questions about software development. There is an active Python community there that you can access. However since you are new and struggling with programming here are some tips.

In your example you aren't creating a file, you are just doing output with print. If you want to create a file you need to open the output file with open(filename, "w") specifying the "w" to indicate you are going to write to the file.

Python makes it easy to open a file and have it closed when you are finished using it. The with keyword creates a block that, when the program control flows out of that block closes the file.

If you want to write to three different files you will have to name them differently. The way to do this is create a variable and increment it each time you open a new file.

Python also makes it easy to read lines of text from a file. Calling in on a file within a for loop will give you the next line of a text fille. Note that the final \n character on the line is included in what is returned. In this case that is what you want since you are going to write it to your output file and file's write expects you supply the \n, unlike print which puts one on for you.

So, putting this all together your program may look like

outnum = 0
with open("test.txt") as infile:
    outnum += 1
    outfile = open(f"test_out{outnum}.txt", "w")
    for line in infile:
        if outfile.closed:
            outfile = open(f"test_out{outnum}.txt", "w")
        if len(line) == 1: # only the end-of-line character
            continue;
        outfile.write(line)
        if line.startswith('$'):
            outfile.close()
            outnum += 1
            continue;
if not outfile.closed: # last line didn't start with $
    outfile.close()

My hope is that you will study this and see how the code weaves together the various aspects of looping over input and keeping the output file open to the current number. Some extensions you could do: have comment lines which start with #; use the split method of string to have comments that can start anywhere on the line; use the re module to remove lines that are all blanks; make the script into a function called when the file is executed; use the unittest module to test your changes.

1
  • Thank you very much for your help. I would need to make a tiny tweak to the code above to handle the line with character "$". Currently that line is stripped out completely in the second file, but I will try to find the solution based on your suggestion and will reply back here. Commented Sep 13, 2020 at 17:09

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.