How to add text to a file in python3 - python-3.x

Let's say i have the following file,
dummy_file.txt(contents below)
first line
third line
how can i add a line to that file right in the middle so the end result is:
first line
second line
third line
I have looked into opening the file with the append option, however that adds the line to the end of the file.

with open("dummy_file.txt", 'r') as file:
lines = file.readlines()
lines.insert(1, "second line\n")
with open("dummy_file.txt", 'w') as output:
output.writelines(lines)
So:
We open the file an read all the lines making a list.
We insert to the list the desired new line, using \n for a new line.
We open the file again but this time to write.
We write all the lines from the list.
But I wouldn't recommend this method, due it hight memory usage (if the file is big).

The standard file methods don't support inserting into the middle of a file. You need to read the file, add your new data to the data that you read in, and then re-write the whole file.

Related

How to append text to existing line in a text file

I need to append text to an existing line in a systemd unit file using NodeJS. The line I need to edit will always start with ExecStart but the line number it occurs on may not always be the same.
So the below example:
ExecStart=/opt/binaries/my-binary.bin
Now needs to be:
ExecStart=/opt/binaries/my-binary.bin --port=5000 --host=localhost
I have the text to be appended in a constant called serviceArguments which is determined by a separate function.

what is the best way to modify a particular line of a csv file without erasing everything?

I have a csv file open with notepad :
I want to modify my csv to replace line 4 with 'Temperature Level Wave Degre':
My code :
with open(file.csv, 'w') as m:
content = m.readlines()
line_4 = (content[3])
line_4.replace(line_4, 'Temperature Level Wave Degre')
My csv is empty!
What is the best way to modify a particular line of a csv file without erasing everything ?
The most efficient code?
Thank you.
Here is a solution using python, however as I mentioned in my comment, there are likely more efficient command line tools (I would use awk)
with open(filename, 'r+') as f:
lines = f.readlines() # read lines and store in list
lines[3] = 'Temperature Level Wave Degre\n' # change line 4, don't forget to add a newline
f.seek(0) # come back to beginning of file
f.writelines(lines) # write the new lines
f.truncate() # ensure we don't keep old stuff from the previous file

Using Selenium to grab contents of lines in a text file

I am trying to use selenium to grab the line of a text file, input that line into an element, click the submit option, and continue to do every line in the txt file until it is done. What I have tried is only pasting in the entire text file which is not what I want. The element I will be sending the keys to is below.
newalias = driver.find_element_by_id('mailbox_alias_source')
I hope this makes sense and you guys can help, Thanks!
Would be a start.
file = open ("data.txt", "r")
lines = file.readlines()
for line in lines:
newalias = driver.find_element_by_id('mailbox_alias_source')
newalias.send_keys(line.strip())
file.close()

How can I insert a text file at specific line of another

I am dynamically generating some SDK code for multiple API sets and need to merge in subsets of files so that my ending import structure works.
I have a file, lets call it methods_to_import.txt of which I have already extractimed the lines I need to insert using:
awk '/method_imports_im_matching/{print}' file_i_need_to_copy_methods_from.rb > method_to_import.txt
I need to insert methods_to_import.txt at a specific line of the main file my_api.rb which looks something like like:
# Models
require 'models/account'
require 'models/account_type'
...
// the line I need to insert the text file into ( ex. line 10 )
# APIs
require 'my_api'
module My Class
...
end
I've figured out ways to overwrite the file completely:
echo "foo" > bar.txt
or Insert a single string at a specific file line: awk 'NR==3{print "Single String, but not the entire file output :("}1' my_api.rb
https://unix.stackexchange.com/questions/271475/insert-text-at-specific-line-number
Perhaps I need to loop each line of the .txt file and insert line by line into the .rb file?
But I cant figure out how to insert the entire text file at a specific line of the existing file. I'm pretty sure it can be done with a combination of sed || awk. Thanks in advance.
will be simpler with sed
$ sed '/insert the text file/r methods_to_import.txt' my_api.rb

Get the last line of a file in groovy

Google doesn't give any great results for getting the last line of a file in groovy so I feel this question is necessary.
How does one get the last line of a file in groovy?
Get all lines, then get the last one:
def lines=new File("/home/user/somefile.txt").readLines()
def lastline=lines.get(lines.size()-1)
Or, if the file is dangerously large:
def last=new File('/home/user/somefile.txt').withReader { r-> r.eachLine {it} }
which is almost identical to asker's answer.
Here's what I ended up with:
new File("/home/user/somefile.txt").eachLine {
lastLine = it
}
.eachLine iterates through each line of the text file and lastLine is set to the current iteration until eachLine finishes going through the file. Pretty straightforward.
How does one get the last line of a file in groovy?
It depends on what you know about the file. If the lines in the file are fixed length then you could look at the file size, divide it by the length of each line and then use random file access to jump to the last line in the file and read it. That would be more efficient than reading the entire file. If you don't know the length of the lines then you are probably going to have to read the entire file and discard everything before the last line you read.

Resources