what is the best way to modify a particular line of a csv file without erasing everything? - python-3.x

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

Related

Is there a faster way to extract lines from a file?

I have a set of files that I need to search through and extract certain lines. Right now, I'm using a for loop but this is proving costly in terms of time. Is there a faster way than the below?
import re
for file in files:
localfile = open(file, 'r')
for line in localfile:
if re.search("Common English Words", line):
words = line.split("|")[0]
# Append words to file words.txt
open("words.txt","a+").write(words + "\n")
Well for one thing, you are creating a new file descriptor every time that you write to the words.txt file.
I ran some tests and found that python garbage collection does in fact close open file descriptors when they become inaccessible (at least in my test case).
However, creating a file descriptor every time that you want to append to a file is going to be costly. For future reference, it is considered good practice to use with as blocks for opening files.
TLDR:
One improvement you could make is to open the file you are writing to just once.
Here is what that would look like:
import re
with open("words.txt","a+") as words_file:
for file in files:
localfile = open(file, 'r')
for line in localfile:
if re.search("Common English Words", line):
words = line.split("|")[0]
# Append words to file words.txt
words_file.write(words + "\n")
Like I said, using with as statements when opening files is considered best practice. We can fully implement this best practice like so:
import re
with open("words.txt","a+") as words_file:
for file in files:
with open(file, 'r') as localfile:
for line in localfile:
if re.search("Common English Words", line):
words = line.split("|")[0]
# Append words to file words.txt
words_file.write(words + "\n")

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()

Is there a way to open a file for the user to read?

I know it's possible for you to open a file and edit it, but is it possible for a python program to open a file so the user can read it? I'm trying to find a way to open up .txt file so the user can see what was written on it.
If you want to print to terminal/command line you could just do something like this.
with open("line_file.txt", "r") as f:
lines = f.readlines()
for line in lines():
print(line)
But make a habit of reading files line by line and stripping it as well.
with open('file.txt','r') as f:
line=f.readline()
while line:
print(line.strip())
line=f.readline()

How can I read and write on the same file without opening / closing it [duplicate]

I'm trying to read from an originally empty file, after a write, before closing it. Is this possible in Python?
with open("outfile1.txt", 'r+') as f:
f.write("foobar")
f.flush()
print("File contents:", f.read())
Flushing with f.flush() doesn't seem to work, as the final f.read() still returns nothing.
Is there any way to read the "foobar" from the file besides re-opening it?
You need to reset the file object's index to the first position, using seek():
with open("outfile1.txt", 'r+') as f:
f.write("foobar")
f.flush()
# "reset" fd to the beginning of the file
f.seek(0)
print("File contents:", f.read())
which will make the file available for reading from it.
File objects keep track of current position in the file. You can get it with f.tell() and set it with f.seek(position).
To start reading from the beginning again, you have to set the position to the beginning with f.seek(0).
http://docs.python.org/2/library/stdtypes.html#file.seek
Seek back to the start of the file before reading:
f.seek(0)
print f.read()

How to add text to a file in python3

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.

Resources