Insert text in between file lines in python - python

I have a file that I am currently reading from using
fo = open("file.txt", "r")
Then by doing
file = open("newfile.txt", "w")
file.write(fo.read())
file.write("Hello at the end of the file")
fo.close()
file.close()
I basically copy the file to a new one, but also add some text at the end of the newly created file. How would I be able to insert that line say, in between two lines separated by an empty line? I.e:
line 1 is right here
<---- I want to insert here
line 3 is right here
Can I tokenize different sentences by a delimiter like \n for new line?

First you should load the file using the open() method and then apply the .readlines() method, which splits on "\n" and returns a list, then you update the list of strings by inserting a new string in between the list, then simply write the contents of the list to the new file using the new_file.write("\n".join(updated_list))
NOTE: This method will only work for files which can be loaded in the memory.
with open("filename.txt", "r") as prev_file, open("new_filename.txt", "w") as new_file:
prev_contents = prev_file.readlines()
#Now prev_contents is a list of strings and you may add the new line to this list at any position
prev_contents.insert(4, "\n This is a new line \n ")
new_file.write("\n".join(prev_contents))

readlines() is not recommended because it reads the whole file into memory. It is also not needed because you can iterate over the file directly.
The following code will insert Hello at line 2 at line 2
with open('file.txt', 'r') as f_in:
with open('file2.txt','w') as f_out:
for line_no, line in enumerate(f_in, 1):
if line_no == 2:
f_out.write('Hello at line 2\n')
f_out.write(line)
Note the use of the with open('filename','w') as filevar idiom. This removes the need for an explicit close() because it closes the file automatically at the end of the block, and better, it does this even if there is an exception.

For Large file
with open ("s.txt","r") as inp,open ("s1.txt","w") as ou:
for a,d in enumerate(inp.readlines()):
if a==2:
ou.write("hi there\n")
ou.write(d)

U could use a marker
#FILE1
line 1 is right here
<INSERT_HERE>
line 3 is right here
#FILE2
some text
with open("FILE1") as file:
original = file.read()
with open("FILE2") as input:
myinsert = input.read()
newfile = orginal.replace("<INSERT_HERE>", myinsert)
with open("FILE1", "w") as replaced:
replaced.write(newfile)
#FILE1
line 1 is right here
some text
line 3 is right here

Related

How to save each line of a file to a new file (every line a new file) and do that for multiple original files

I have 5 files from which i want to take each line (24 lines in total) and save it to a new file. I managed to find a code which will do that but they way it is, every time i have to manually change the number of the appropriate original file and of the file i want to save it to and also the number of each line every time.
The code:
x1= np.loadtxt("x_p2_40.txt")
x2= np.loadtxt("x_p4_40.txt")
x3= np.loadtxt("x_p6_40.txt")
x4= np.loadtxt("x_p8_40.txt")
x5= np.loadtxt("x_p1_40.txt")
with open("x_p1_40.txt", "r") as file:
content = file.read()
first_line = content.split('\n', 1)[0]
with open("1_p_40_x.txt", "a" ) as f :
f.write("\n")
with open("1_p_40_x.txt", "a" ) as fa :
fa.write(first_line)
print(first_line)
I am a beginner at python, and i'm not sure how to make a loop for this, because i assume i need a loop?
Thank you!
Since you have multiple files here, you could define their names in a list, and use a list comprehension to open file handles to them all:
input_files = ["x_p2_40.txt", "x_p4_40.txt", "x_p6_40.txt", "x_p8_40.txt", "x_p1_40.txt"]
file_handles = [open(f, "r") for f in input_files]
Since each of these file handles is an iterator that yields a single line every time you iterate over it, you could simply zip() all these file handles to iterate over them simultaneously. Also throw in an enumerate() to get the line numbers:
for line_num, files_lines in enumerate(zip(*file_handles), 1):
out_file = f"{line_num}_p_40.txt"
# Remove trailing whitespace on all lines, then add a newline
files_lines = [f.rstrip() + "\n" for f in files_lines]
with open(out_file, "w") as of:
of.writelines(files_lines)
With three files:
x_p2_40.txt:
2_1
2_2
2_3
2_4
x_p4_40.txt:
4_1
4_2
4_3
4_4
x_p6_40.txt:
6_1
6_2
6_3
6_4
I get the following output:
1_p_40.txt:
2_1
4_1
6_1
2_p_40.txt:
2_2
4_2
6_2
3_p_40.txt:
2_3
4_3
6_3
4_p_40.txt:
2_4
4_4
6_4
Finally, since we didn't use a context manager to open the original file handles, remember to close them after we're done:
for fh in file_handles:
fh.close()
If you have files with an unequal number of lines and you want to create files for all lines, consider using itertools.zip_longest() instead of zip()
In order to read each of your input files, you can store them in a list and iterate over it with a for loop. Then we add every line to a single list with the function extend() :
inputFiles = ["x_p2_40.txt", "x_p4_40.txt", "x_p6_40.txt", "x_p8_40.txt", "x_p1_40.txt"]
outputFile = "outputfile.txt"
lines = []
for filename in inputFiles:
with open(filename, 'r') as f:
lines.extend(f.readlines())
lines[-1] += '\n'
Finally you can write all the line to your output file :
with open(outputFile, 'w') as f:
f.write(''.join(lines))

How do I split each line into two strings and print without the comma?

I'm trying to have output to be without commas, and separate each line into two strings and print them.
My code so far yields:
173,70
134,63
122,61
140,68
201,75
222,78
183,71
144,69
But i'd like it to print it out without the comma and the values on each line separated as strings.
if __name__ == '__main__':
# Complete main section of code
file_name = "data.txt"
# Open the file for reading here
my_file = open('data.txt')
lines = my_file.read()
with open('data.txt') as f:
for line in f:
lines.split()
lines.replace(',', ' ')
print(lines)
In your sample code, line contains the full content of the file as a str.
my_file = open('data.txt')
lines = my_file.read()
You then later re-open the file to iterate the lines:
with open('data.txt') as f:
for line in f:
lines.split()
lines.replace(',', ' ')
Note, however, str.split and str.replace do not modify the existing value, as strs in python are immutable. Also note you are operating on lines there, rather than the for-loop variable line.
Instead, you'll need to assign the result of those functions into new values, or give them as arguments (E.g., to print). So you'll want to open the file, iterate over the lines and print the value with the "," replaced with a " ":
with open("data.txt") as f:
for line in f:
print(line.replace(",", " "))
Or, since you are operating on the whole file anyway:
with open("data.txt") as f:
print(f.read().replace(",", " "))
Or, as your file appears to be CSV content, you may wish to use the csv module from the standard library instead:
import csv
with open("data.txt", newline="") as csvfile:
for row in csv.reader(csvfile):
print(*row)
with open('data.txt', 'r') as f:
for line in f:
for value in line.split(','):
print(value)
while python can offer us several ways to open files this is the prefered one for working with files. becuase we are opening the file in lazy mode (this is the prefered one espicialy for large files), and after exiting the with scope (identation block) the file io will be closed automaticly by the system.
here we are openening the file in read mode. files folow the iterator polices, so we can iterrate over them like lists. each line is a true line in the file and is a string type.
After getting the line, in line variable, we split (see str.split()) the line into 2 tokens, one before the comma and the other after the comma. split return new constructed list of strings. if you need to omit some unwanted characters you can use the str.strip() method. usualy strip and split combined together.
elegant and efficient file reading - method 1
with open("data.txt", 'r') as io:
for line in io:
sl=io.split(',') # now sl is a list of strings.
print("{} {}".format(sl[0],sl[1])) #now we use the format, for printing the results on the screen.
non elegant, but efficient file reading - method 2
fp = open("data.txt", 'r')
line = None
while (line=fp.readline()) != '': #when line become empty string, EOF have been reached. the end of file!
sl=line.split(',')
print("{} {}".format(sl[0],sl[1]))

Python 3 text files - I want to add add user input to the end of each line of text in file 1 then copy the new lines into file 2

File1 contains 5 lines with text
File2 is empty
Q. when I run the code below I only get the first 4 lines appended to File2?
Any suggestions?
File1 = open("MyFile.txt", "r")
for Line in File1:
Line = Line.strip()
AddData = input( "extra text")
NewLine = Line + ":" + AddData # : as field seperator
File2 = open("MyFile2.txt", "a")
File2.write(NewLine+"\n")
print(NewLine) #remove
File2.close
You're not closing the file write
You need to use:
File2.close()
and not
File2.close
Without the parenthesis you only name the function without actually calling it and then it is not executed
And the write(newline) method is only passing your line to a buffer, it's write to file only when buffer is full or when you call open() or close()
Your first 4 lines were written because you called the open() method after them

Remove a specific letter from a specific line in a file in python

This is probably a duplicate, but I couldn't find my answer anywhere.
I have a text file and I want to remove a specific character from a specific line.
Here's one example:
#textfile.txt
Hey!
1234/
How are you//?
9/23r
How can I remove the slash from the second line?
The output should be:
#textfile.txt
Hey!
1234
How are you//?
9/23r
I've got no code and no clue on how to do this.
I run python 2.7.14 on Debian.
You can read the file line by line and identify the line you want to modify. Then identify the index/location of the character you want to modify(remove).
Replace it with blank and write the text line by line into the file.
#opeing the .txt file
fp = open("data.txt", "r")
#reading text line by line
text= fp.readlines()
#searching for character to remove
char = text[1][-2]
#removing the character by replacing it with blank
text[1] = text[1].replace(char, "")
#opeing the file in write mode
fw = open("data.txt", "w")
#writing lines one by one
for lines in text:
fw.write(lines)
#closing the file
fw.close()
A simple solution is to read in the entire file, find the line that you want to change, change it, and write out all of the content again:
filename = 'textfile.txt'
original = '1234/'
replacement = '1234'
# Open file for reading and read all lines into a list
with open('textfile.txt') as f:
lines = f.readlines()
# Find the line number (index) of the original string
index = lines.index(original + '\n')
# Replace this element of the list
lines[index] = replacement + '\n'
# Write out the modified lines to disk
with open(filename, 'w') as f:
f.writelines(lines)

Split text file into lines, Python

I want to split a text file in python, using the following peice of code:
inputfile = open(sys.argv[1]).read()
for line in inputfile.strip().split("\n"):
print line
the problem is, that it's read the first 12 lines only!! the file is large more than 10 thousand lines!
What is the possible reason!
Thanks,
with open(sys.argv[1]) as inputfile:
for line in inputfile:
print(line)
Use readlines() which will generate list automatically and no need to read by "\n".
Try this:
text = r"C:\Users\Desktop\Test\Text.txt"
oFile = open(text, 'r')
line = oFile.readline()[:-1]
while line:
splitLine = line.split(' ')
print splitLine
line = oFile.readline()[:-1]
oFile.close()
I use this style to iterate through huge text files at work

Categories

Resources