I have file contains text like Hello:World
#!/usr/bin/python
f = open('m.txt')
while True:
line = f.readline()
if not line :
break
first = line.split(':')[0]
second = line.split(':')[1]
f.close()
I want to put the string after splitting it into 2 variables
On the second iteration i get error
List index out of range
it doesn't break when the line is empty , i searched the answer on related topics and the solution was
if not line:
print break
But it does not work
If there's lines after an empty line (or your text editor inserted an empty line at the end of the file), it's not actually empty. It has a new line character and/or carriage return
You need to strip it off
with open('m.txt') as f:
for line in f:
if not line.strip():
break
first, second = line.split(':')
You can do this relatively easily by utilizing an optional feature of the built-in iter() function by passing it a second argument (called sentinel in the docs) that will cause it to stop if the value is encountered while iterating.
Here's what how use it to make the line processing loop terminate if an empty line is encountered:
with open('m.txt') as fp:
for line in iter(fp.readline, ''):
first, second = line.rstrip().split(':')
print(first, second)
Note the rstrip() which removes the newline at the end of each line read.
Your code is fine, I can't put a picture in a comment. It all works, here:
Related
I have csv file with single column, in some cases the last value gets more space and create new row, here I need to find out and append it to the previous line
for eg :
my python code :
with open("01.csv", 'r+') as file:
text = str()
for line in file:
if line[0:3] == "2021":
text = "{} {}".format(text, line.strip())
else:
text = "{}\n{}".format(text, line.strip())
file.seek(0)
file.write(text[1:])
How to remove || this in last and append next line to it in all occurrence.
Line no 10 to be appended to line no 9 and line no 21 to be appended to line no 20 nd so on..
You can't "append next line" if you haven't seen it yet. Your solution has to know that all appends are complete before otherwise acting on a line, which means you need to buffer the next line.
I think you're trying to re-compose the whole file in text as you go, which isn't a great model for file handling. And if your test were working, the actions are actually the wrong way around - you want to include the newline when "20" starts the line. I suggest that instead you write to another new file or simply correct the issue on the fly as below.
with open("01.csv", 'r+') as file:
complete_line = None
for line in file:
if complete_line is None:
initial_action()
complete_line = line
elif line[0:2] == "20": # compatible with next 79 years
act_on(complete_line)
complete_line = line
else:
complete_line += line
act_on(complete_line)
where intial_action and act_on are functions for you to implement.
This program takes in a txt file and prints out the first word of each line. It works perfectly but at the end it prints out this error
Traceback (most recent call last):
File "C:/Users/vipku/PycharmProjects/untitled/test.py", line 7, in <module>
print(f.readline().split()[0])
IndexError: list index out of range
This is the code that I wrote
f = open("example.txt", "r")
for line in f:
for first in line:
print(f.readline().split()[0])
Check if the line is empty before getting the first element:
f = open("example.txt", "r")
lines = f.readlines()
for line in lines:
if line.strip():
print(line.split()[0])
Note that this:
f = open("example.txt", "r")
for line in f:
for first in line:
actually means:
open file "example.txt" for reading
for every line in that file:
for every character in that line:
So this means you do readline more times that actual number of lines - due to this you get empty str from readline, as docs says if f.readline() returns an empty string, the end of the file has been reached, while a blank line is represented by '\n', a string containing only a single newline.
It is enough to use single for if you want to deal with line after line. You should check for blank lines (lines consisting of single newline - using .split at them result in empty list), so solution might looks like:
f = open("example.txt", "r")
for line in f:
words = line.split()
if words:
print(words[0])
f.close()
I harness fact that empty lists are False-y and non-empty list True-y, so print will be executed only if words has at least 1 element. Note that files should be closed after usage. You might do it implicitly or use with open... approach instead. You might learn about latter from this realpython tutorial.
I am new to Python.
Scenario:
apple=gravity search this pattern in file
search for apple if exist fetch corresponding value for apple,
if it is apple=gravity then case pass .
file structure (test.txt )
car=stop
green=go
apple=gravity
Please provide some suggestions as to how I can search value for key in file using Python
Sample:
f = open('test.txt', 'r')
wordCheck="apple=gravity";
for line in f:
if 'wordCheck' == line:
print ('found')
else:
print ('notfound')
break
Split your line with =
Check if apple is present in your first index! If true then, print the second index!
Note:
While reading lines from file, the '\n' character will be present. To get your line without \n read you content from file and use splitlines()!
To make it clean, strip the spaces from the beginning and end of your line to avoid glitches caused by spaces at the beginning and end of your line!
That is,
f = open('test.txt', 'r')
for line in map(str.strip,f.read().splitlines()):
line = line.split('=')
if 'apple' == line[0]:
print line[1]
else:
print ('notfound')
Output:
notfound
notfound
gravity
Hope it helps!
Iterating through the file directly as you are doing, is just fine, and considered more 'Pythonic' than readlines() (or indeed read().splitlines()).
Here, I strip the newline from each line and then split by the = to get the two halves.
Then, I test for the check word, and if present print out the other half of the line.
Note also that I have used the with context manager to open the file. This makes sure that the file is closed, even if an exception occurs.
with open('test.txt', 'r') as f:
wordcheck="apple"
for line in f:
key, val = line.strip().split('=')
if wordcheck == key:
print (val)
else:
print ('notfound')
I'm trying to write a code that looks for a specific text in a file and gets the line after.
f = open('programa.txt','r')
for line in f:
if (line == "[Height of the board]\n"):
## skip to next line and saves its content
print(line)
Set a flag so you know to grab the next line.
f = open('programa.txt','r')
grab_next = False
for line in f:
if grab_next:
print(line)
grab_next = line == "[Height of the board]\n"
File objects are iterators in Python; while the for loop uses the iterator protocol implicitly, you can invoke it manually yourself when you need to skip ahead:
with open('programa.txt') as f:
for line in f:
if line == "[Height of the board]\n":
# skip to next line and saves its content
line = next(f)
print(line)
Your example code is unclear on where to store the next line, so I've stored it back to line, making the original line header disappear. If the goal was to print only that line and break, you could use:
with open('programa.txt') as f:
for line in f:
if line == "[Height of the board]\n":
# skip to next line and saves its content
importantline = next(f)
print(importantline)
break
Problems like this are almost always simpler when you look back rather than trying to look ahead. After all, finding out the last line is trivial; you just store it in a variable! In this case, you want to save the current line if the previous line was the header:
f = open('programa.txt', 'r')
last = ""
for line in f:
if last == "[Height of the board]\n":
height = int(line.strip()) # for example
break # exit the loop once found (optional)
last = line
Another question.
This program counts and numbers every line in the code unless it has a hash tag or if the line is empty. I got it to number every line besides the hash tags. How can I stop it from counting empty lines?
def main():
file_Name = input('Enter file you would like to open: ')
infile = open(file_Name, 'r')
contents = infile.readlines()
line_Number = 0
for line in contents:
if '#' in line:
print(line)
if line == '' or line == '\n':
print(line)
else:
line_Number += 1
print(line_Number, line)
infile.close()
main()
You check if line == '' or line == '\n' inside the if clause for '#' in line, where it has no chance to be True.
Basically, you need the if line == '' or line == '\n': line shifted to the left :)
Also, you can combine the two cases, since you perform the same actions:
if '#' in line or not line or line == '\n':
print line
But actually, why would you need printing empty stings or '\n'?
Edit:
If other cases such as line == '\t' should be treated the same way, it's the best to use Tim's advice and do: if '#' in line or not line.strip().
You can skip empty lines by adding the following to the beginning of your for loop:
if not line:
continue
In Python, the empty string evaluates to the boolean value True. In case, that means empty lines are skipped because this if statement is only True when the string is empty.
The statement continue means that the code will continue at the next pass through the loop. It won't execute the code after that statement and this means your code that's counting the lines is skipped.