I am trying to replace multiple strings in a file.
My file may have some contents like this:
file1:
#groovy
some test
some more test
REPLACE_1
REPLACE_OPTIONAL_1
REPLACE_2
end test
I am trying to use fileinput module to replace above text but its not working as expected. My method is something like this:
import fileinput
def replace_method():
file_path = './file1.txt'
try:
with fileinput.FileInput(file_path, inplace=True, backup=".bak") as file:
for line in file:
print (line.replace('REPLACE_1', 'replaced_value1'), end='')
print (line.replace('REPLACE_OPTIONAL_1', 'replaced_value2'), end='')
print (line.replace('REPLACE_OPTIONAL_2', 'replaced_value3'), end='')
print (line.replace('REPLACE_2', 'replaced_value4'), end='')
except Exception as e:
print (str(e))
Above code works but it prints everyline 4 times in the new modified file. I believe this is something to do with line.replace which Imight be using wrongly.
Can you please help me fixing this.
Please let me know if you need more information.
Don't print 4 times
import fileinput
def replace_method():
file_path = './file1.txt'
try:
with fileinput.FileInput(file_path, inplace=True, backup=".bak") as file:
for line in file:
line = line.replace('REPLACE_1', 'replaced_value1')
line = line.replace('REPLACE_OPTIONAL_1', 'replaced_value2')
line = line.replace('REPLACE_OPTIONAL_2', 'replaced_value3')
line = line.replace('REPLACE_2', 'replaced_value4')
print (line, end='')
except Exception as e:
print (str(e))
The problem is that you are printing the line four times instead of one. The fix could look like:
import fileinput
def replace_method():
file_path = './file1.txt'
try:
with fileinput.FileInput(file_path, inplace=True, backup=".bak") as file:
for line in file:
line.replace('REPLACE_1', 'replaced_value1')
line.replace('REPLACE_OPTIONAL_1', 'replaced_value2')
line.replace('REPLACE_OPTIONAL_2', 'replaced_value3')
line.replace('REPLACE_2', 'replaced_value4')
print(line, end='')
except Exception as e:
print (str(e))
Related
When I run this code, a NameError traceback error pops up, even though it should be handled by the exception. Why is that?
The function call argument is intentionally misspelled.
filename_cats = "cats.txt"
filename_dogs = "dogs.txt"
def readlines(filename):
"""read lines from a text file"""
try:
with open(filename) as f:
lines = f.readlines()
string = ''
for line in lines:
string += line
except (NameError, FileNotFoundError):
print(f"The file {filename} was not found.")
else:
print(string)
readlines(filename_cat)
It's because the error happens here:
👇
readlines(filename_cat) 👈
☝️
Not anywhere in here:
try:
with open(filename) as f:
lines = f.readlines()
string = ''
for line in lines:
string += line
except (NameError, FileNotFoundError):
A try..except block can only catch errors happening literally within it, not anything happening before or after it.
I have been following the 'Python for dummies' book and there is one example that doesn't print out the result as I expected.
class Error(Exception):
pass
class NotEnoughStuffError(Error):
pass
try:
thefile = open('people.csv')
line_count = len(thefile.readlines())
if line_count < 2:
raise NotEnoughStuffError
except NotEnoughStuffError:
print('Not Enough Stuff')
except FileNotFoundError:
print('File not found')
thefile.close()
else:
for line in thefile:
print(line)
thefile.close()
print('Success!')
Question 1: When it prints, it should show all the lines from thefile. However, it only prints 'Success!' Why the content from thefile was not printed?
Question 2: I replaced the code:
class Error(Exception):
pass
class NotEnoughStuffError(Error):
pass
with
class NotEnoughStuffError(Exception):
pass
Do they return the same result? Is 'Exception' a built-in class in Python?
Problem is because you used readlines() and it moved pointer to the end of file and when you later use for line in thefile: then it tries to read from end of file. And it reads nothing from the end of file and it display nothing.
You would have assing list with lines to variable
all_lines = thefile.readlines()
line_count = len(all_lines)
and later use this list
for line in all_lines:
print(line)
Or you would have to move pointer to the beginning of file before you try to read again data
thefile.seek(0)
for line in thefile:
print(line)
I have an input file which looks like
===========================
__A= 2.3
__b= 3.26
===========================
__ctx= 4.2
===========================
__itermax= 100
__errmax= 1e-07
Using this inputfile a collection of outputs within a different code( not implemented in python) has been generated. I am now trying to write some Python scripts to read this input file as well as other generated outputs to perform postproccessing analysis.
I thus would like to extract the value of each parameter(A, b, ctx, ...) by a python script. Please note that this input file is distinct from the setting file discussed here as I can not perform any modification on the structure of the input file.
I have tried
import sys
try:
directory_name=sys.argv[1]
print(directory_name)
except:
print('Please pass directory_name')
input_file = directory_name +"input.txt"
with open(input_file) as fin:
for line in fin:
exec(line)
The error that I am encountering after running the code is
File "code.py", line 14, in <module>
exec(line)
File "<string>", line 1
===========================
^
SyntaxError: invalid syntax
Any suggestion on improving this code, or with a different outputting method (e.g. as a dictionary), to obtain the values of the parameters is helpful.
Do you wanna exec the string "==================" ?
This string is not a python code.
There is a lazy way, use try ... except ... to resolve this.
import sys
try:
directory_name=sys.argv[1]
print(directory_name)
except:
print('Please pass directory_name')
input_file = directory_name +"input.txt"
with open(input_file) as fin:
for line in fin:
try:
exec(line)
except Exception as e:
print(e)
Another way is you can remove all unuseful strings before you exec them.
Try a simple regular expression:
import re
e = r'^__(.*?)=(.*?)$'
with open('data.txt') as f:
print(dict(re.findall(e, f.read(), re.M)))
This will print:
{'A': ' 2.3', 'b': ' 3.26', 'ctx': ' 4.2', 'itermax': ' 100', 'errmax': ' 1e-07'}
Executing random lines of code from a file is risky, and a bit 'hacky'. If you really want to do it, the easiest way to fix your code is to just try each line:
import sys
try:
directory_name=sys.argv[1]
print(directory_name)
except:
print('Please pass directory_name')
input_file = directory_name +"input.txt"
with open(input_file) as fin:
for line in fin:
try:
exec(line)
except:
print("Line invalid: {}".format(line))
for extract thei value use re.search
import re
import sys
textfile = sys.argv[1]
f = open(textfile, 'r').readlines()
for l in f:
extract = l.rstrip()
try:
f = re.search('__A= (.*)', extract)
return True
except:
return False
valueA = f.group(1)
print valueA
you first have to check "line" makes sens to be executed.
the problem is when line = "========="
you can use :
if line.startwith("===")
continue
to skip it.
or
if line.startwith("__"):
exec(line)
to avoid exectuting unknown stuff
I'm fairly new to coding and am having some issues printing a text file.
Here's my file:
Player1: 1
Player2: 3
Here's my code:
try:
scoreTable = open("scoreTable.txt", "r")
line = scoreTable.readlines()
for i in range(0, (len(line))):
print(scoreTable.read(len(line[i].strip("\n"))))
scoreTable.close()
except FileNotFoundError:
pass
At the moment its just printing whitespace.
I'm probably missing something obvious or have gone down the wrong road altogether, so any help would be appreciated.
Thanks in advance.
Just use the below code sample to print the whole file.
try:
with open("scoreTable.txt", "r" ) as scoreTable:
file_content = scoreTable.read()
print str(file_content)
except FileNotFoundError as e:
print e.message
You are performing read operation on scoreTable.txt twice, which is not required.
try:
scoreTable = open("scoreTable.txt", "r")
lines = scoreTable.readlines()
#here in lines you have whole file stored so no need to try to read from files variable again
for line in lines:
print line
scoreTable.close()
except FileNotFoundError:
pass
While we are on this subject use with statement to read files(so you wont have to keep track to close the file)
with open("scoreTable.txt", "r" ) as f:
lines = f.readlines()
for line in lines:
print line
I want this to recursively call the next file, listed in a manually inputted file. It is the first word listed in the file.
The current error messege is:
OSError: [Errno 22] Invalid argument: 'file1.txt\n'.
This is my current code:
import os
def crawl(fname):
infile = open(fname, 'r')
if os.stat(fname)[6]==0:
return "Visiting {}".format(fname)
infile.close()
else:
print ("Visiting {}".format(fname))
lines = infile.read().splitlines()
nextfile = lines[0].strip()
for line in lines:
crawl(nextfile)
Try:
import os
def crawl(fname):
with open(fname, "r") as infile:
print("Visiting {}".format(fname))
if os.stat(fname).st_size:
lines = infile.read().splitlines()
for line in lines:
crawl(line)
I'm pretty sure the problem is that you're getting a newline at the end of the filename you are reading from the first file. You can easily fix it, by using the strip method to remove the newline:
nextfile = lines[0].strip()