I am processing a file line by line. Each line is checked, whether it contains a given text. Then, the next line needs to be assigned to the variable
i_line = iter(file)
for i_line in file:
if text in i_line:
#Go to the next line
line = next(i_line, None) #A problem
break
How to increment iterator i_line so as to point to the next line of the file? Both constructions do not work for me
next(i_line, None)
i_line.next()
Just do next(f).
Something like
>>> with open('testFile.txt', 'r') as f:
for line in f:
if 'cat' in line:
final_string = next(f)
So, for an input text file of
My Name is ABC.
I am a male.
My pet is a cat.
It's name is Ronald.
I hate rats.
The above code gives
>>> final_string
"It's name is Ronald.\n"
Use line = file.next() instead of line = next(i_line, None).
Here's a way of processing a file with next().
with open(filename) as file:
line = next(file, None)
while line:
print(line.strip())
line=next(file, None)
Using both the for line in file iterator and next would print every other line:
with open(filename) as file:
for line in file:
print(line.strip())
line = next(file,None)
Related
I'm making a joke program that has a text file storing jokes. On program load, it grabs all the lines from the file and assigns them to a jokes list Everything but the remove joke function is working. Whenever you call remove joke, it ends up re-writing every line in the text file to an empty string instead of the selected line
When running this function, it does remove the joke from the jokes list properly
def remove_joke():
for i in range(len(jokes)):
print(f"{i}\t{jokes[i]}")
remove_index = int(input("Enter the number of the joke you want to remove:\t"))
with open("jokes.txt", "r") as f:
lines = f.readlines()
with open("jokes.txt", "w") as f:
for line in lines:
print(line)
if line == jokes[remove_index]:
f.write("")
jokes.remove(jokes[remove_index])
Instead of
if line == jokes[remove_index]:
f.write("")
you want:
if line != jokes[remove_index]:
f.write(line+'\n')
Or even:
if line != jokes[remove_index]:
print(line, file=f)
I want to search for particular text and replace the line if the text is present in that line.
In this code I replace line 125, but want to replace dynamically according to the text:
file = open("config.ini", "r")
lines = file.readlines()
lines[125] = "minimum_value_gain = 0.01" + '\n'
f.writelines(lines)
f.close()
How do I make it that if a line has:
minimum_value_gain =
then replace that line with:
minimum_value_gain = 0.01
There is no reason for you to manually parse a config.ini file textually. You should use configparser to make things much simpler. This library reads the file for you, and in a way converts it to a dict so processing the data is much easier. For your task you can do something like:
import configparser
config = configparser.ConfigParser()
config.read("config.ini")
for section in config:
if config.has_option(section, "minimum_value_gain"):
config.set(section, "minimum_value_gain", "0.01")
with open("config.ini", 'w') as f:
config.write(f)
Since you are replacing complete line so if statement will do the trick for you, no need to replace text
#updated make sure one line doesn't have both values
file = open("config.ini", "r")
lines=file.readlines()
newlines = []
for line in lines:
if "minimum_value_gain" in line:
line = "minimum_value_gain = 0.01" + '\n'
if "score_threshold" in line:
line = "Values you want to add"+'\n'
newlines.append(line)
f.writelines(newlines)
f.close()
Little bit messy and not optimized but get's the job the, first readlines and inserts the next_text to the given pos(line). If the line doesn't exists Raises IndexError, else writes to the file
def replace_in_file(filename: str, search_text: str, string_to_add: str) -> None:
with open(filename, "r+") as file_to_write:
lines = file_to_write.readlines()
file_to_write.seek(0)
file_to_write.truncate()
for line in lines:
if line.startswith(search_text):
line = line.rstrip("\n") + string_to_add + "\n"
file_to_write.write(line)
replace_in_file("sdf.txt", "minimum_value_gain", " = 0.01")
You can use also the regex library of Python.
Here is an example.
It is better not to read and write in the same file, that is not good practice. Write in a different file then eventually rename it.
import re
pattern = 'minimum_value_gain'
string_to_replace = 'minimum_value_gain = 0.01\n'
file = open("config.ini", "r")
fileout = open("new_config.ini", "a")
lines=file.readlines()
newlines = [string_to_replace if re.match(pattern, line) else line for line in lines]
f.close()
fileout.writelines(lines)
fileout.close()
You can rename the file afterwards :
import os
os.remove("config.ini")
os.rename("new_config.ini", "config.ini")
Set the string you would like to look for (match_string = 'example')
Have a list output_list that is empty
Use with open(x,y) as z: (this will automatically close the file after completion)
for each line in file.readlines() - run through each line of the file
The if statement adds your replacement line if the match_string is in the line, else just the adds the line
NOTE: All variables can be any name that is not reserved (don't call something just 'list')
match_string = 'example'
output_list = []
with open("config.ini", "r") as file:
for line in file.readlines():
if match_string in line:
output_list.append('minimum_value_gain = 0.01\n')
else:
output_list.append(line)
Maybe not ideal for the first introduction to Python (or more readable) - But I would have done the problem as follows:
with open('config.ini', 'r') as in_file:
out_file = ['minimum_value_gain = 0.01\n' if 'example' in line else line for line in in_file.readlines()]
To replace a specific text in a string
a = 'My name is Zano'
b = a.replace('Zano', 'Zimmer')
I want to access a file (C:\Programmer\Test.txt
), find a string inside that file beginning with 'SS' and replace everything after that on the same line with a new string 'C:\Test\Flash'
The code below prints out the line I want to modify but I can't seem to find a suitable function that will replace everything after the 'SS' with the new string.
import re
for line in open('C:\Programmer\Build\Test.txt'):
if line.startswith('SS'):
print(line)
storedline = line
print(storedline)
You can do
file_path = 'C:\Programmer\Build\Test.txt'
new_line_content = 'C:\Test\Flash'
output = []
with open(file_path, 'r') as infile:
line = infile.readline()
while line:
if line[0:2] == 'SS':
output.append('SS{}\n'.format(new_line_content))
else:
output.append(line)
line = infile.readline()
with open(file_path, 'w') as outfile:
outfile.write(''.join(output))
Note that here the detection of the line(s) if line[0:2] == 'SS' is based on interpreting literally your requirement 'find a string inside that file beginning with 'SS''
So I want to look in the file something and when I read a line that begins with # I want to print something in the front of the line and in the end of it.
file = open("something.py","r")
infile = file.readlines()
for line in infile:
if line.find("#") !=-1:
index = line.find("#")
print("BLABLABLA",the line that begins with #,"BLABLABLA", end="")
How about this:
# Open file for reading
with open("infile.txt", "r") as infile:
# Open another file for writing
with open("outfile.txt", "w") as outfile:
# Read each line from the input file
for line in infile.readlines():
# Check if line begins with keyword "Hello"
if line.startswith("Hello"):
# If it does, prepend and append something to the line
line = "Prepend! >>> " + line.strip() + " <<< Append!"
# Finally, write the line to outfile
outfile.write(line + "\n")
Input:
Hello, this is a line.
Hello, this is another line.
Goodbye, these were all the lines
Output:
Prepend! >>> Hello, this is a line. <<< Append!
Prepend! >>> Hello, this is another line. <<< Append!
Goodbye, these were all the lines
Simple & short. The last two lines will change depending on your flag and what you want to actually do with the line read.
with open('input.txt', 'r') as f:
for line in f:
if line.startswith('#'):
print('!!!' + line.strip() + '!!!')
Currently I have:
for line in f:
if line == promble:
print("check")
I want to make the program print the line after the line I have selected. Help.
If you want to test a line in a file, and if it matches print the next line in the file, try:
selected = False
for line in f:
if selected:
print line
selected = False
if line == promble:
selected = True
Use enumerate
for index,line in enumerate(f):
if line == promble:
print f[index+1]
Your file object f has an __iter__ attribute, so you can apply next to get the next item in your loop:
for line in f:
if line == promble:
print(next(f)) # prints next line after the current one
If f is neither a file object nor an iterator, you can call iter on f to make one:
it = iter(f)
for line in it:
if line == promble:
print(next(it))
If f was already an iterator, calling iter on f will return f again, so it still works fine.