Unexpected results when converting while loop to for loop - python-2.7

I have a while loop that generally works well but I would like to convert it to a for loop. The while loop is as follows:
with open(filename) as a:
while tally != c:
line = a.readline()
c = line.strip()
Where I open a file, read each line until I find the line I am interested in. The for loop is as follows:
with open(filename) as a:
for line in enumerate (a):
if tally == c:
break
elif tally != c:
c = line
It appears that the loop just reads to the end of the file every time and turns the variable c into a tuple consisting of a random number and the last line of the file. I know the string contained in tally exists in the file because the while loop performs the intended function.

Fixed code:
with open(filename) as a:
for line in a:
if tally == c:
break
else:
c = line.strip()
Two issues:
for line in enumerate(a) means line gets a tuple on each iteration of the line number and the actual line from the file. Read up on enumerate to understand its use.
c = line is different from c = line.strip() in your original loop.

Instead of c=line it must be c=line.strip().

Related

Skip rows while reading txt file in FORTRAN [duplicate]

I'm writing in fortran (90). My program must read file1, do something with every line of it and write result to file2. But the problem - file1 has some unneeded information in first line.
How can I skip a line from input file using Fortran?
The code:
open (18, file='m3dv.dat')
open (19, file='m3dv2.dat')
do
read(18,*) x
tmp = sqrt(x**2 + 1)
write(19, *) tmp
end do
First line is a combination of text and numbers.
One possible solution has already been presented to you which uses a "dummy variable", but I just wanted to add that you don't even need a dummy variable, just a blank read statement before entering the loop is enough:
open(18, file='m3dv.dat')
read(18,*)
do
...
The other answers are correct but this can improve conciseness and (thus) readability of your code.
Perform a read operation before the do loop that reads whatever is on the first line into a "dummy" variable.
program linereadtest
implicit none
character (LEN=75) ::firstline
integer :: temp,n
!
!
!
open(18,file='linereadtest.txt')
read(18,*) firstline
do n=1,4
read(18,'(i3)') temp
write(*,*) temp
end do
stop
end program linereadtest
Datafile:
This is a test of 1000 things that 10
of which do not exist
50
100
34
566
!ignore the space in between the line and the numbers, I can't get it to format
open (18, file='m3dv.dat')
open (19, file='m3dv2.dat')
read(18,*) x // <---
do
read(18,*) x
tmp = sqrt(x**2 + 1)
write(19, *) tmp
end do
The line added just reads the first line and then overwrites it with the seconde on the first iteration.

how to not remove space in file

how to keep the space betwen the words?
in the code it deletes them and prints them in column.. so how to print them in row and with the space?
s ='[]'
f = open('q4.txt', "r")
for line in f:
for word in line:
b = word.strip()
c = list(b)
for j in b:
if ord(j) == 32:
print ord(33)
if ord(j) == 97:
print ord(123)
if ord(j) == 65:
print ord(91)
chr_nums = chr(ord(j) - 1)
print chr_nums
f.close()
Short answer: remove the word.strip() command - that's deleting the space. Then put a comma after the print operation to prevent a newline: print chr_nums,
There are several problems with your code aside from what you ask about here:
ord() takes a string (character) not an int, so ord(33) will fail.
for word in line: will be iterating over characters, not words, so word will be a single character and for j in b is unnecessary.
Take a look at the first for loop :
for line in f:
here the variable named 'line' is actually a line from the text file you are reading. So this 'line' variable is actually a string. Now take a look at the second for loop :
for word in line:
Here you are using a for loop on a string variable named as 'line' which we have got from the previous loop. So in the variable named 'word' you are not going to get a word, but single characters one by one. Let me demonstrate this using a simple example :
for word in "how are you?":
print(word)
The output of this code will be as follows :
h
o
w
a
r
e
y
o
u
?
You are getting individual characters from the line and so you don't need to use another for loop like you did 'for j in b:'. I hope this helped you.

Crystal get from n line to n line from a file

How can I get specific lines in a file and add it to array?
For example: I want to get lines 200-300 and put them inside an array. And while at that count the total line in the file. The file can be quite big.
File.each_line is a good reference for this:
lines = [] of String
index = 0
range = 200..300
File.each_line(file, chomp: true) do |line|
index += 1
if range.includes?(index)
lines << line
end
end
Now lines holds the lines in range and index is the number of total lines in the file.
To prevent reading the entire file and allocating a new array for all of its content, you can use File.each_line iterator:
lines = [] of String
File.each_line(file, chomp: true).with_index(1) do |line, idx|
case idx
when 1...200 then next # ommit lines before line 200 (note exclusive range)
when 200..300 then lines << line # collect lines 200-300
else break # early break, to be efficient
end
end

Python- Writing all results from a loop to a variable

I have a .txt file with dozens of columns and hundreds of rows. I want to write the results of the entirety of two specific columns into two variables. I don't have a great deal of experience with for loops but here is my attempt to loop through the file.
a = open('file.txt', 'r') #<--This puts the file in read mode
header = a.readline() #<-- This skips the strings in the 0th row indicating the labels of each column
for line in a:
line = line.strip() #removes '\n' characters in text file
columns = line.split() #Splits the white space between columns
x = float(columns[0]) # the 1st column of interest
y = float(columns[1]) # the 2nd column of interest
print(x, y)
f.close()
Outside of the loop, printing x or y only displays the last value of the text file. I want it to have all the values of the specified columns of the file. I know of the append command but I am unsure how to apply it in this situation within the for loop.
Does anyone have any suggestions or easier methods on how to do this?
Make two lists x and y before you sart the loop and append to them in the loop:
a = open('file.txt', 'r') #<--This puts the file in read mode
header = a.readline() #<-- This skips the strings in the 0th row indicating the labels of each column
x = []
y = []
for line in a:
line = line.strip() #removes '\n' characters in text file
columns = line.split() #Splits the white space between columns
x.append(float(columns[0])) # the 1st column of interest
y.append(float(columns[1])) # the 2nd column of interest
f.close()
print('all x:')
print(x)
print('all y:')
print(y)
Your code only binds the value of the last element. I'm not sure that is your entire codes, but if you want to keep add the values of the column, I would suggest appending it to the array then print it outside of loop.
listx = []
listy = []
a = open('openfile', 'r')
#skip the header
for line in a:
#split the line
#set the x and y variables.
listx.append(x)
listy.append(y)
#print outside of loop.

Why does this code only read the first line rather than the whole .txt file?

I have a code here on Python 2.7 that is supposed to tell me the frequency of a letter or word within a single text file.
def frequency_a_in_text(textfile, a):
"""Counts how many "a" letters are in the text file.
"""
try:
f = open(textfile,'r')
lines = f.readlines()
f.close()
except IOError:
return -1
tot = 0
for line in lines:
split = str(line.split())
k = split.count(s)
tot = tot + k
return tot
print frequency_a_in_text("RandomTextFile.txt", "a")
There's a little bit of extra coding in there - the "try" and "except", but that's just telling me that if I can't open the text file, then it'll return a "-1" to me.
Whenever I run it, it seems to just read the first line and tell me how many "a" letters there are.
You are returning out of the function after the first iteration of your loop.
The return statement should be outside of the loop.
for line in lines:
split = str(line.split())
k = split.count(s)
tot = tot + k
return tot