Python 2.7.8 for line iteration error - python

I want to iterate over all lines in a file with the following script
import sys
infile = open("test.txt")
infile.read()
for line in infile
if line.find("This") != -1
print line
infile.close()
Unfortunately, I am getting this error message:
File "getRes.py", line 6
for line in infile
^
SyntaxError: invalid syntax
I've been trying for an hour to figure out what is the error and I am still not able to find it. Can you tell me what is wrong and how to fix it?
PS: I am using Python 2.7.8, I would like to use this old version instead of a more recent version.

You need a colon after any line that introduces a block in Python.
for line in infile:
if line.find("This") != -1:

There's another mistake in your code, you don't need:
infile.read()
Because it reads all contens of infile and doesn't save it to any variable. And what is more important it moves you to the end of file, so there's no more lines to read.
In addition there's no need to manualy close file, it's better to use with statement:
with open("test.txt") as infile:
for line in infile:
# do what you want
# here file will be close automaticaly, when we exit "with" scope.

Related

I am new in python I was trying to perform read/write operations but I got this error ->FileNotFoundError: [Errno 2] No such file or directory error?

I found this solution from stackoverflow but will i have to add this piece of code every time i write a code to perform read/write operations.
Or is there any long term solution available for this ?
import os
path = "E:\Python\learn"
os.chdir(path)
f = open('text.txt')
data = f.read()
print(data)
f.close()
I think you need a way to read same file multiple times in your python code. Use file.seek() to jump to a specific position in a file. However, think about whether it is really necessary to go through the file again. An Example for file.seek:
with open(name, 'r+') as file:
for line in file:
# Do Something with line
file.seek(0)
for line in file:
# Do Something with line, second time
Incase you want to re-iterate the file second time and don't want to open the file again, you can follow this syntax:
with open(name, 'r+') as file:
for line in file:
# Do Something with line
for line in file:
# Do Something with line, second time

get distinct values from file via python

everyone!
I have one file containing one column with only numbers (Paramkey.txt) and i need to read the file and get distinct values and write them in another .txt file. Can someone help with the code? So far the code looks like this
infile=open("Paramkey.txt", "r")
outfile=open("distkey.txt", "w")
for line in infile:
outfile.write(set(infile)
else:
pass
infile.close()
outfile.close()
And i get Syntax error, something with the else statement.
So i managed to finish the program and it's working:
infile=open("Paramkey.txt", "r")
outfile=open("distkey.txt", "w")
for line in infile:
output=set(line.strip() for line in infile)
print >> outfile, "distincts:", output
infile.close()
outfile.close()
and i just want to add i used the "print >>" instead of "print()" statement, because my python is version 2.7.x not 3.x

Script not reading end of file new line

I am writing a script to validate if a given file has a blank line at the end or not. I am reading that file into python using code
with open(input_file, "r") as file_data:
for line in file_data:
if line.strip() == "":
print "found empty line"
When i open the test file in sublime, i can see that sublime shows 370 lines and the 370th line is just an empty line. however, when i use that file as test in my python script, i don't see my if condition being true. is python library already skipping an empty-end-of-file-new-line?
UPDATE
little bit more context.
The data was generated using linux system. These files were then copied to MAC and were re-process. During this re-processing the data written line by line with command file_handle.write(data + "\n").
I hope this gives more context.
Comparison for identity with the empty string is a delicate matter. Do this instead:
with open(input_file, "r") as file_data:
for line in file_data:
if not line.strip():
print "found empty line"
Works for me with Python 3.6.

Combined effect of reading lines twice?

As a practice, I am learning to reading a file.
As is obvious from code, hopefully, I have a file in working/root whatever directory. I need to read it and print it.
my_file=open("new.txt","r")
lengt=sum(1 for line in my_file)
for i in range(0,lengt-1):
myline=my_file.readlines(1)[0]
print(myline)
my_file.close()
This returns error and says out of range.
The text file simply contains statements like
line one
line two
line three
.
.
.
Everything same, I tried myline=my_file.readline(). I get empty 7 lines.
My guess is that while using for line in my_file, I read up the lines. So reached end of document. To get same result as I desire, I do I overcome this?
P.S. if it mattersm it's python 3.3
No need to count along. Python does it for you:
my_file = open("new.txt","r")
for myline in my_file:
print(myline)
Details:
my_file is an iterator. This a special object that allows to iterate over it.
You can also access a single line:
line 1 = next(my_file)
gives you the first line assuming you just opened the file. Doing it again:
line 2 = next(my_file)
you get the second line. If you now iterate over it:
for myline in my_file:
# do something
it will start at line 3.
Stange extra lines?
print(myline)
will likely print an extra empty line. This is due to a newline read from the file and a newline added by print(). Solution:
Python 3:
print(myline, end='')
Python 2:
print myline, # note the trailing comma.
Playing it save
Using the with statement like this:
with open("new.txt", "r") as my_file:
for myline in my_file:
print(myline)
# my_file is open here
# my_file is closed here
you don't need to close the file as it done as soon you leave the context, i.e. as soon as you continue with your code an the same level as the with statement.
You can actually take care of all of this at once by iterating over the file contents:
my_file = open("new.txt", "r")
length = 0
for line in my_file:
length += 1
print(line)
my_file.close()
At the end, you will have printed all of the lines, and length will contain the number of lines in the file. (If you don't specifically need to know length, there's really no need for it!)
Another way to do it, which will close the file for you (and, in fact, will even close the file if an exception is raised):
length = 0
with open("new.txt", "r") as my_file:
for line in my_file:
length += 1
print(line)

How can I add a new line of text at top of a file?

I'm developing a simple program which makes a Python script executable, and I'm working in the part which adds the interpreter path (#! /usr/bin/python). I tried to do it, but instead of adding a new line, it replaces the current and removes part of the next line. What I'm doing wrong?
I uploaded the source code to Ubuntu Pastebin: http://pastebin.ubuntu.com/1032683/ The wrong code is between lines 28 and 31:
wfile = open(file, 'r+')
if wfile.readline() != "#! /usr/bin/python\n":
wfile.seek(0)
wfile.write("#! /usr/bin/python\n")
Using Python 2.7.2 with an iPad 2 (Python for iOS), also using 2.5.1 in the same iPad (Cydia port) for testing.
You can't do what you're trying to do. Seeking to the beginning of a file and doing a write will overwrite from that position, not append.
The only way to add a line in the middle (or beginning) of a file is to write out a new file with the data inserted where you want it to.
Joe is correct in that you have to can't just "insert" lines at the beginning of the file. Here is a solution for you, however:
with open(my_python_script, "r+") as f:
first_line = f.readline()
if first_line != "#! /usr/bin/python\n":
lines = f.readlines()
f.seek(0)
f.write("#! /usr/bin/python\n")
f.write(first_line)
f.writelines(lines)
To add/replace the first line in each file given at a command line:
#!/usr/bin/env python
import fileinput
shebang = "#! /usr/bin/python\n"
for line in fileinput.input(inplace=1):
if fileinput.isfirstline() and line != shebang:
print shebang,
if not line.startswith("#!"):
print line,
else:
print line,

Categories