Python Forum

Full Version: How to append and drop to next line while slice/indexing
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm practicing with opening, reading and appending to files. One of my goals was to open the file for the second time within the program and append a sliced segment from the original file. I was able to write the sliced segment, but I am lost on how to get it to drop to the next line. \n doesn't work in slicing. I have included the source code first and then divided the code with the output on the bottom.

with open("PythonSourceCode", "w") as python_file:
    content = python_file.write("with open(\"PythonSourceCode\", \"w\") as python_file:")

with open("PythonSourceCode", "a+") as My_Python_File:
    My_Python_File.seek(0)
    New_Content = My_Python_File.write("\nThis is practice")

with open("PythonSourceCode") as The_Final_Product:
    The_Final = The_Final_Product.read()

print(The_Final)

The_Final_Product.close()

with open("PythonSourceCode", "a+") as change:
    change.seek(0)
    new = change.read()
    newest = change.write(new[11:28])

with open("PythonSourceCode") as One_More:
    Last_One = One_More.read()

print(Last_One)
Output:
with open("PythonSourceCode", "w") as python_file: This is practice with open("PythonSourceCode", "w") as python_file: This is practicePythonSourceCode"
I'm running Ubuntu with python version 3.6
Probably not the answer you are looking for, but automatic newline is added with print(). So one can do:

with open('sample.txt', 'w') as f:
    print('First row', file=f)

with open('sample.txt', 'a') as f:
    print('Second row', file=f)
Which results the sample.txt to have following content:

Output:
First row Second row
Why not just write('\n') after writing the slice?
just try
newest = change.write('\n'+new[11:28])