I am trying to make a simple program that takes a text file as input and then prints out a five day temperature forecast from the file. I am having trouble with getting the correct value to print from the delimited string. Any ideas where I went wrong here? My output is attached below.
print("File:")
f = input()
a = open(f, 'r')
b = a.read()
c = b.split(',')
a.close()
count = 1
for i in c:
print("Day {}: {}".format(count, c))
count = count + 1
.close() should be used on the file object.
you should use a.close() to close file.
b is a string resulting of the "read()" executed on the a object (your file)
Once you have that problem solved you can continue trying if your program is working as you expected.
Edit:
Now that you've solved that problem, there's something else I think you should look into.
On your print statement, you ouput the c array, wich comes from splitting the first line of the file, and only the first one. You're not looping through the file lines. That's why you always get the same array as output for each day.
If your goal is to print one number per day, then your code should be:
for i in c:
print("Day {}: {}".format(count, i))
count = count + 1
If your goal is to repeat this process for every line inside the file, then you should do something like:
for line in f:
#your code
Related
I am a beginner in python, and I have a problem when I want to read my numeric data file that contains more lines. My data in the input file contains rows that include a counter number, three float numbers, and finally, a character letter that all of them separated by space.it look like this:
1 12344567.143 12345678.154 1234.123 w
2 23456789.231 23413456.342 4321.321 f
I want to assign each item in the line to a specific parameter that I can use them to other steps.
like this "NO"=first item "X"=second item "Y"=third item "code"=forth item
I am trying to write it as follow:
f1=open('t1.txt','r')
line: float
for line in f1:
print(line.split(', ',4))
f1=float
select(line.split('')
nob: object(1)=int(line[1, 1])
cnt = 0
print(nob)
cnt +=1
but received more error each time when I run the program. Anyone can help me?
The error is probably due to the wrong indentation: in Python indentation is part of the syntax. It would be helpful if you also included the error message in your question.
How about this:
all_first_numbers = []
with open('t1.txt', 'r') as f:
for line in f:
values = line.split()
first_number = int(values[0])
second_number = float(values[1])
letter_code = values[4]
# If you want to save all the first numbers in one array:
all_first_numbers.append(first_number)
I'm struggling to get my code to work. I've been supplied with some variables to work with: The variable P is my file path, designated as content/textfiles/empty.txt; while the variable S is my string, designated as parrot. The end goal is to find out how many times Parrot (S) appears in my text file (P). The following is the variables and information I have been supplied with, and immediately following is my crude code that is attempting to complete my task:
import sys
P= sys.argv[1]
S= sys.argv[2]
file = open(P,'r')
data = file.read()
count = 0
if S in P:
count += 1
print(count)
file.close()
The primary issue is that I am supposed to have a return of 3 for output, but my code is only counting 1 occurrence, but I have no idea why.
[Answer previously posted on question]:
file = open(P,'r')
data = file.read()
count = data.count(S)
print(count)
trying to find a way of making this process work pythonically or at all. Basically, I have a really long text file that is split into lines. Every x number of lines there is one that is mainly uppercase, which should roughly be the title of that particular section. Ideally, I'd want the title and everything after to go into a text file using the title as the name for the file. This would have to happen 3039 in this case as that is as many titles will be there.
My process so far is this: I created a variable that reads through a text file tells me if it's mostly uppercase.
def mostly_uppercase(text):
threshold = 0.7
isupper_bools = [character.isupper() for character in text]
isupper_ints = [int(val) for val in isupper_bools]
try:
upper_percentage = np.mean(isupper_ints)
except:
return False
if upper_percentage >= threshold:
return True
else:
return False
Afterwards, I made a counter so that I could create an index and then I combined it:
counter = 0
headline_indices = []
for line in page_text:
if mostly_uppercase(line):
print(line)
headline_indices.append(counter)
counter+=1
headlines_with_articles = []
headline_indices_expanded = [0] + headline_indices + [len(page_text)-1]
for first, second in list(zip(headline_indices_expanded, headline_indices_expanded[1:])):
article_text = (page_text[first:second])
headlines_with_articles.append(article_text)
All of that seems to be working fine as far as I can tell. But when I try to print the pieces that I want to files, all I manage to do is print the entire text into all of the txt files.
for i in range(100):
out_pathname = '/sharedfolder/temp_directory/' + 'new_file_' + str(i) + '.txt'
with open(out_pathname, 'w') as fo:
fo.write(articles_filtered[2])
Edit: This got me halfway there. Now, I just need a way of naming each file with the first line.
for i,text in enumerate(articles_filtered):
open('/sharedfolder/temp_directory' + str(i + 1) + '.txt', 'w').write(str(text))
One conventional way of processing a single input file involves using a Python with statement and a for loop, in the following way. I have also adapted a good answer from someone else for counting uppercase characters, to get the fraction you need.
def mostly_upper(text):
threshold = 0.7
## adapted from https://stackoverflow.com/a/18129868/131187
upper_count = sum(1 for c in text if c.isupper())
return upper_count/len(text) >= threshold
first = True
out_file = None
with open('some_uppers.txt') as some_uppers:
for line in some_uppers:
line = line.rstrip()
if first or mostly_upper(line):
first = False
if out_file: out_file.close()
out_file = open(line+'.txt', 'w')
print(line, file=out_file)
out_file.close()
In the loop, we read each line, asking whether it's mostly uppercase. If it is we close the file that was being used for the previous collection of lines and open a new file for the next collection, using the contents of the current line as a title.
I allow for the possibility that the first line might not be a title. In this case the code creates a file with the contents of the first line as its names, and proceeds to write everything it finds to that file until it does find a title line.
I'm only just beginning my journey into Python. I want to build a little program that will calculate shim sizes for when I do the valve clearances on my motorbike. I will have a file that will have the target clearances, and I will query the user to enter the current shim sizes, and the current clearances. The program will then spit out the target shim size. Looks simple enough, I have built a spread-sheet that does it, but I want to learn python, and this seems like a simple enough project...
Anyway, so far I have this:
def print_target_exhaust(f):
print f.read()
#current_file = open("clearances.txt")
print print_target_exhaust(open("clearances.txt"))
Now, I've got it reading the whole file, but how do I make it ONLY get the value on, for example, line 4. I've tried print f.readline(4) in the function, but that seems to just spit out the first four characters... What am I doing wrong?
I'm brand new, please be easy on me!
-d
To read all the lines:
lines = f.readlines()
Then, to print line 4:
print lines[4]
Note that indices in python start at 0 so that is actually the fifth line in the file.
with open('myfile') as myfile: # Use a with statement so you don't have to remember to close the file
for line_number, data in enumerate(myfile): # Use enumerate to get line numbers starting with 0
if line_number == 3:
print(data)
break # stop looping when you've found the line you want
More information:
with statement
enumerate
Not very efficient, but it should show you how it works. Basically it will keep a running counter on every line it reads. If the line is '4' then it will print it out.
## Open the file with read only permit
f = open("clearances.txt", "r")
counter = 0
## Read the first line
line = f.readline()
## If the file is not empty keep reading line one at a time
## till the file is empty
while line:
counter = counter + 1
if counter == 4
print line
line = f.readline()
f.close()
I just started python, any suggestions would be greatly appreciated. I'm reading a table generated by another program and pulling out 2 numbers from each line, I'll call them a and b. (they are saved as flux and observed in my program) I need to take these two numbers from each line and format them like this-
(a,b),(a,b),(a,b) ect.
Each consecutive parenthesis is from the consecutive line, first a,b is from line 1, second a,b is from line 2, etc. I need to read the entire table however, the table length will vary.
This is what I have so far. It can read the table and pull out the numbers I need, however, I don't know how to put the numbers into the proper format. I want to say something recursive would be most efficient but I'm unsure of how to do that. Thank you in advance.
#!/usr/bin/python
file = open("test_m.rdb")
while 1:
line = file.readline()
i = line.split()
flux = i[2]
observed = i[4]
if not line:
break
with open("test_m.rdb") as inf:
results = [(i[2],i[4]) for i in (line.split() for line in inf)]
result_string = ",".join(str(res) for res in results)
or a more general formatter:
result_string = ", ".join("('{2}', '{4}')".format(*res) for res in results)
Very simple solution:
with open('data') as data:
print ', '.join('(%s, %s)' % (x.split()[2], x.split()[4])
for x in data.readlines())
Just use readlines to iterate over the lines in the file.
assuming that two values you got are str1 and str2
//inside a loop which iterates through your values
strTable = strTable + ['('+str1+')','('+str2+')']
hope oit will work, if it dont, comment , i will solve it.