I have two different functions in my program, one writes an output to a txt file (function A) and the other one reads it and should use it as an input (function B).
Function A works just fine (although i'm always open to suggestions on how i could improve).
It looks like this:
def createFile():
fileName = raw_input("Filename: ")
fileNameExt = fileName + ".txt" #to make sure a .txt extension is used
line1 = "1.1.1"
line2 = int(input("Enter line 2: ")
line3 = int(input("Enter line 3: ")
file = (fileNameExt, "w+")
file.write("%s\n%s\n%s" % (line1, line2, line3))
file.close()
return
This appears to work fine and will create a file like
1.1.1
123
456
Now, function B should use that file as an input. This is how far i've gotten so far:
def loadFile():
loadFileName = raw_input("Filename: ")
loadFile = open(loadFileName, "r")
line1 = loadFile.read(5)
That's where i'm stuck, i know how to use this first 5 characters but i need line 2 and 3 as variables too.
f = open('file.txt')
lines = f.readlines()
f.close()
lines is what you want
Other option:
f = open( "file.txt", "r" )
lines = []
for line in f:
lines.append(line)
f.close()
More read:
https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files
from string import ascii_uppercase
my_data = dict(zip(ascii_uppercase,open("some_file_to_read.txt"))
print my_data["A"]
this will store them in a dictionary with lettters as keys ... if you really want to cram it into variables(note that in general this is a TERRIBLE idea) you can do
globals().update(my_data)
print A
Related
Hi i want to create a code that read a text file and print the average of each person in the file, i have this in the folder
boys.txt
ed lin,3,1,4,2
thomas block,6,3,3
Functions.py
def read_txt(file_txt):
file = open(file_txt, "r")
lines = file.readlines()
file.close()
return lines
from Functions import read_txt
file_txt = input("input file: ")
read_txt(file_txt)
lines = (sum(lines)/len(lines))
print(lines)
so i want to print something like
ed lin: 2.5
thomas block: 4
but i dont know how to continue and with my code i get error
Try changing your other file to:
from Functions import read_txt
file_txt = input("input file: ")
lines read_txt(file_txt)
lines = '\n'.join(['%s: %s' % (line.split(',')[0], sum(list(map(int, line.strip().split(',')[1:]))) / len(line.strip().split(',')[1:])) for line in lines])
print(lines)
Output:
ed lin: 2.5
thomas block: 4
I don't know why you are not allowed to use format, but without using it, it would be a little too tedious... In the meantime, here is another way you can do.
with open("boys.txt", "r") as f:
contents = f.read()
lines = contents.strip().split("\n")
for l in lines:
boy = l.split(",")
length = len(boy)
score = 0
for i in range(1, length):
score += int(boy[i])
average = score / (length-1)
print("{}: {}".format(boy[0], average))
You could also use
from Functions import read_txt
file_txt = input("input file: ")
with open(file_txt, 'r') as f:
lines = f.readlines()
for line in lines:
name = line[0: line.index(',')]
data = [int(num) for num in (line[line.index(',')+1:].split(','))]
nums = len(data)
data = sum(data)
print(f"{name}: {data/nums}")
I am provided with a txt file including lots of different letters.
e.g:
ab sbfdjd iojdig
ds fjk sdfji oer
lkjäp foküeeferf
How can I check how often for example the letter "j" was used in line 1, line 2 and line 3 and store this information in an array/list?
So for this certain example
print(NumberOfJInLine[0])
would output:
2
Try this
def NumberOfStringInLine(index, string_to_find):
print(string_to_find, lines_of_file[index])
return lines_of_file[index].count(string_to_find)
def NumberOfJInLine(index):
return NumberOfStringInLine(index, "j")
lines_of_file = open("text.txt", "r").readlines()
print(NumberOfStringInLine(0, "jd"))
print(NumberOfJInLine(0))
You don't need the other function I added but it adds flexibility.
Alternatively:
def AccumulateAppearances():
with open("text.txt", "r") as file:
for line in file:
yield line.count("j")
for n in AccumulateAppearances():
print(n)
seekLetter = "j"
occur = {}
with open("{your filename}", "r") as file:
for nbLine,line in enumerate(file):
occur[nbLine] = line.count(seekLetter)
for line in occur.keys():
print("line {0} : ".format(line) + str(occur[line]) + seekLetter)
you can do it more easily with a dictionary
I have the code below to write out a list of N-grams in Python.
from nltk.util import ngrams
def word_grams(words, min=1, max=6):
s = []
for n in range(min, max):
for ngram in ngrams(words, n):
s.append(' '.join(str(i) for i in ngram))
return s
email = open("output.txt", "r")
for line in email.readlines():
with open('file.txt', 'w') as f:
for line in email:
prnt = word_grams(email.split(' '))
f.write("prnt")
email.close()
f.close()
when I print out the word_grams it prints out the files correctly but when it comes to writing the output into files.txt it doesn't work. The "file.txt" is empty.
So I guess the problem must be within these lines of codes:
for line in email.readlines():
with open('file.txt', 'w') as f:
for line in email:
prnt = word_grams(email.split(' '))
f.write("prnt")
email.close()
f.close()
1) the final f.close() does something else than what you want (f inside the loop is another object)
2) You name the file "file.txt" but want the output in "files.txt". Are you sure that you are looking in a correct file?
3) You are overwriting the file for each line in the email. Perhaps the with statement for "file.txt" should be outside the loop.
4) You are writing "prnt" instead of prnt
Something like this?
def word_grams(words, min=1, max=6):
s = []
for n in range(min, max):
for ngram in ngrams(words, n):
s.append(' '.join(str(i) for i in ngram))
return s
with open("output.txt", "r") as email:
with open('file.txt', 'w') as f:
for line in email.readlines():
prnt = word_grams(line.split(' '))
for ngram in prnt:
f.write(ngram)
I don't know what you are trying to accomplish exactly, but it seems that you would like to apply the function word_grams to every word in the file "output.txt" and save the output to a file called "file.txt", probably one item per line.
With these assumptions, I would recommend to rewrite your iteration in this manner:
words = []
# load words from input
with open("output.txt") as f:
for line in f:
words += line.strip().split(" ")
# generate and save output
grams = apply(word_grams, words)
with open("file.txt", "w") as f:
f.write("\n".join(grams))
However, this code assumes that the function word_grams is working properly.
Your code in loop:
for line in email:
did not run!
Because after email.readlines()run,the variable email is empty.
You can do some test like fallows:
email = open("output.txt", "r")
for line in email.readlines():
print '1'
for line in email:
print '2'
if you have 3 lines in your output.txt,after you run this test,you will get:
1
1
1
in the output.
And you can do a test like this:
email = open("output.txt", "r")
email.readlines()
you will see a list with the lines in your output.txt.
but when you run email.readlines()again,you will get an empty list!
so,there should be the problem.your variable email is empty in your second loop.
Am Writing a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:
X-DSPAM-Confidence: 0.8475
I want to count these lines and extract the floating point values from each of the lines and compute the average of those values. Can I please get some help. I just started programming so I need something very simple. This is the code I have already written.
fname = raw_input("Enter file name: ")
if len(fname) == 0:
fname = 'mbox-short.txt'
fh = open(fname,'r')
count = 0
total = 0
#Average = total/num of lines
for line in fh:
if not line.startswith("X-DSPAM-Confidence:"): continue
count = count+1
print line
Try:
total += float(line.split(' ')[1])
so that total / count gives you the answer.
Iterate over the file (using the context manager ("with") handles the closing automatically), looking for such lines (like you did), and then read them in like this:
fname = raw_input("Enter file name:")
if not fname:
fname = "mbox-short.txt"
scores = []
with open(fname) as f:
for line in f:
if not line.startswith("X-DSPAM-Confidence:"):
continue
_, score = line.split()
scores.append(float(score))
print sum(scores)/len(scores)
Or a bit more compact:
mean = lambda x: sum(x)/len(x)
with open(fname) as f:
result = mean([float(l.split()[1]) if line.startswith("X-DSPAM-Confidence:") for l in f])
A program like the following should satisfy your needs. If you need to change what the program is looking for, just change the PATTERN variable to describe what you are trying to match. The code is written for Python 3.x but can be adapted for Python 2.x without much difficulty if needed.
Program:
#! /usr/bin/env python3
import re
import statistics
import sys
PATTERN = r'X-DSPAM-Confidence:\s*(?P<float>[+-]?\d*\.\d+)'
def main(argv):
"""Calculate the average X-DSPAM-Confidence from a file."""
filename = argv[1] if len(argv) > 1 else input('Filename: ')
if filename in {'', 'default'}:
filename = 'mbox-short.txt'
print('Average:', statistics.mean(get_numbers(filename)))
return 0
def get_numbers(filename):
"""Extract all X-DSPAM-Confidence values from the named file."""
with open(filename) as file:
for line in file:
for match in re.finditer(PATTERN, line, re.IGNORECASE):
yield float(match.groupdict()['float'])
if __name__ == '__main__':
sys.exit(main(sys.argv))
You may also implement the get_numbers generator in the following way if desired.
Alternative:
def get_numbers(filename):
"""Extract all X-DSPAM-Confidence values from the named file."""
with open(filename) as file:
yield from (float(match.groupdict()['float'])
for line in file
for match in re.finditer(PATTERN, line, re.IGNORECASE))
I am trying to create a program that gives the user a short quiz and create a score, which I have done, then I would like to add them to a list in a .txt file. In the program I will ask them their name, so say I have a list such as this;
Bob,7
Bill,5
Jane,6
and someone takes the quiz and inputs the name Bob and gets a score 4 the list will update to;
Bob,4
Bill,5
Jane,6
or someone new takes a quiz, Sarah it will change to;
Bob,4
Bill,5
Jane,6
Sarah,7
So far I have;
import random
file = open("scores.txt", "r")
UserScore=random.randint(0,10)
lines = file.readlines()
file.close()
student=input('What is your name? ')
file = open("scores.txt", "w")
for line in lines:
line = line.strip()
name, score = line.strip().split(",")
if name!=student:
file.write(line)
else:
file.write(name +',' +str(UserScore))
I've randomised the score for now to make it easier to read, however that will be from what the user answered correctly, and I thought this code would read the file then check each name from each line and if the name they entered is the same to the name in the list the line will be replaced with the name and score. However, the file just ends up blank, what am I doing wrong?
Here is what I think is a better idea using the Python pickle module:
In [1]: import pickle
In [2]: scores={'Bob':75, 'Angie':60, 'Anita':80} #create a dict called scores
In [3]: pickle.dump(scores,open('scores.dat','wb')) #dump the pickled object into the file
In [4]: !ls scores.dat #verify that the file has been created
scores.dat
In [5]: !cat scores.dat #list out the file
(dp0
S'Bob'
p1
I75
sS'Angie'
p2
I60
sS'Anita'
p3
I80
s.
In [9]: tscores = pickle.load(open('scores.dat','rb')) #Verification: load the pickled object from the file into a new dict
In [10]: tscores #Verification: list out the new dict
Out[10]: {'Angie': 60, 'Anita': 80, 'Bob': 75}
In [11]: scores == tscores #Verify that the dict object is equivalent to the newly created dict object
Out[11]: True
I tried your code and the first time you run it, then you rewrite the file in one single line. So the next time you run the script on this single line file, you get an unpack exception in the split function and hence you write nothing to the file, resulting in an empty file.
A solution could be to add the newline char again when writing the lines to the file.
import random
file = open("scores.txt", "r")
UserScore=random.randint(0,10)
lines = file.readlines()
file.close()
student=input('What is your name? ')
file = open("scores.txt", "w")
for line in lines:
line = line.strip()
name, score = line.strip().split(",")
if name!=student:
file.write(line + '\n')
else:
file.write(name +',' +str(UserScore) + '\n')
This should do what you want
import random
file = open("scores.txt", "r")
UserScore=random.randint(0,10)
lines = file.readlines()
file.close()
student=input('What is your name? ')
flag = True
file = open("scores.txt", "w")
for line in lines:
line = line.strip()
name, score = line.strip().split(",")
if name!=student:
file.write(line + '\n')
else:
file.write(name +',' +str(UserScore) + '\n')
flag = False
if flag:
file.write(student +',' +str(UserScore) + '\n')
I adjusted a bit of your code and took the liberty to remove the random part and name, score part. But I got some working code. I assume you can make it work for your situation.
file = open("scores.txt", "r+")
lines = file.readlines()
file.close()
us = 15
student = input('What is your name? ')
ls = []
file = open("scores.txt", "r+")
found_student = False
for line in lines:
line = line.strip()
ls = line.split(",")
print("Parsing: " + str(ls))
if not line:
print("Empty line")
pass
elif ls[0] != student:
file.write(line + "\n")
else:
found_student = True
file.write(ls[0] + ',' + str(us) + "\n")
if not found_student:
file.write(student + ',' + str(us) + "\n" )
file.close()