Python -- function to read file and sort info [closed] - python

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
Restaurant sorting. The text file scores.txt contains a series of local restaurant ratings. Each line looks like this:
Restaurant Name: Rating
I'm trying to write a program that reads the file and then spits out the ratings In alphabetical order by restaurant.
These are the contents of the scores.rtf file:
Pancho Villa:3
Andalu:3
Urbun Burger:1
El Toro:5
Casa Thai:2
Taqueria Cancun:2
Little Baobab:1
Charanga:3
Irma's Pampanga:5
Bay Blend Coffee and Tea:3
Giordano Bros:2
Two Amy's: 5
Chef Geoff: 3
I'm not sure where to start with this.

Let's think through this. You have an input with a regular format: a name and a value, separated by a colon :. You'll need to open the file and read each line, then split the line into two parts, name and value. Think about what kind of data structure would be best for holding these values. Once you've read through the file and closed it, you just need to sort your data structure alphabetically, and print out the contents. Easy enough?

import operator
with open('scores.txt') as infile:
for stuff in sorted([line.strip().split(":") for line in infile], key=lambda iGotThisFromStackOverflow: [operator.itemgetter(0)(iGotThisFromStackOverflow)][0]):
print(stuff)

Related

Why is reading from a file not working after using a function? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
My code is supposed to find the occurrence of words in a text. For some reason, after using this function, the reading method from this specific textwon't work(empty lists for .readlines() method and nothing for .read()). The code is:
def counter(new):
words = dict()
lines=new.readlines()
for line in lines:
text=line.split()
for word in text:
if word not in words:
words[word]=1
else: words[word]+=1
return [tuple(x) for x in words.items()]
I haven't found any mistake that can cause this.
I am assuming new is the result of calling open(..), which should be a file handle that you are passing into the function. Calling readlines() is exhausting it, so trying to read from the file using the same handle won't work. Either open a new handle, or you can call new.seek(0) (better option than opening a completely new handle - although there are some cases where the same handle will be returned again, but lets not dive too deep into that here) to move the index to the beginning of the file.

Trying to make a function that copies the content of one file and writes it to another [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have a question that states
Write a function fcopy() that takes as input two file names (as strings) and copies the content of the first file into the second.
and I want to know how to go about solving this.
My first file is named example, and the second file is named output, both text files are in .txt format, and the path to them are
"C:\Users\HOME\Desktop\Introduction to Computing\Lab\assignments\example.txt"
and "C:\Users\HOME\Desktop\Introduction to Computing\Lab\assignments\output.txt"
You are not to ask StackOverflow to do your homework for you. Feeling generous though...
First of all, read this: https://docs.python.org/3.3/library/shutil.html It's the Python 3 docs for the shutil module. It will give high-level functions for reading/writing files (I/O).
from shutil import copyfile
copyfile(locationOfSource, locationOfDestination)
An important thing to note is that "\" (back-slash) signifies non-literal text, so "\n" means new line, NOT just "\n". This is rarely mentioned and had me stumped when I first learnt escape characters. To do the back-slash that you want within a string, you MUST use "\" instead of "\".
The commenters below your answer are correct, please read the information given to you by StackOverflow about asking questions. Also, welcome to the site.
If you really need to, you could write a simple wrapper function to accomplish this:
def copy_file(orig_file_name, copy_file_name):
with open(orig_file_name, 'r') as orig_file, open(copy_file_name, 'w+') as cpy_file:
orig_file = orig_file.read()
cpy_file.write(orig_file)
But as #Frogboxe has already said, the correct way to copy a file is to used the shutil library:
import shutil
shutil.copy(target_file, copy_file)

Count characters in each line of a file? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Any tips on how to count the amount of characters in each line of a text file, to then compare them using python?
It would be helpful to have an idea of what the end goal of your code is. What information do you want to gain from comparing the number of characters on a line? I would have written this as a comment, but it's not yet an option for me since I just joined.
If you're completely lost and don't know where to begin, here are some general bits of code to get you started (this is using Python 3.x):
file = open("YourFileName.txt", "r")
stringList = file.readlines()
The first line will open (read, hence the "r") the file in question. The second line of code goes through each line in the file and assigns them to a variable I called stringList. stringList is now a list, in which each element is a string corresponding to one line of your text file.
So,
print(stringList)
should return
['line0', 'line1', 'line2', 'line3', etc...]
It's possible that stringList could look like
['line0\n', 'line1\n', 'line2\n', 'line3\n', etc...]
depending on how your file is formatted. In case you didn't know, the '\n' is a newline character, equivalent to hitting enter on the keyboard.
From there you can create another list to hold the length of each line, and then loop through each element of stringList to store the lengths.
lengthList = []
for line in stringList:
lengthList.append(len(line))
len(line) takes the number of characters in a string and converts it to the equivalent integer value. Your lengthList will then contain how many characters are on each line, stored as ints. If there are '\n's, you may want to use len(line) - 1, depending on what you want to do with the lengths.
I hope this is helpful; I can't help with the comparisons until you provide some code and explain more specifically what you want to accomplish.

Python function,issue with input file [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have function written by a colleague working in same field. So I know I should write script to execute python code,but issue of how the format of the input bbfile looks like bothers me.As I see fidlines read all the content,correct?My may concern is bbfile(tab delimited in my case),should it have three columns one for freq,other for breal and third for bimag?
def bbcalfunc(bbfile,nfreqlst):
fid=file(bbfile,'r')
fidlines=fid.readlines()
#define the delimiter
if bbfile.find('.txt')>=0:
delimiter='\t'
elif bbfile.find('.csv')>=0:
delimiter=','
freq=[]
breal=[]
bimag=[]
for ii in range(1,len(fidlines)):
linestr=fidlines[ii]
linestr=linestr.rstrip()
linelst=linestr.split(delimiter)
if len(linelst)>2:
freq.append(float(linelst[0]))
breal.append(float(linelst[1]))
bimag.append(float(linelst[2]))
else:
pass
freq=np.array(freq)
breal=np.array(breal)
bimag=np.array(bimag)
nfreq=np.log10(np.array(nfreqlst))
brinterp=interpolate.splrep(freq,breal)
brep=1E3*interpolate.splev(nfreq, brinterp)
biinterp=interpolate.splrep(freq,bimag)
bip=1E3*interpolate.splev(nfreq, biinterp)
return brep,bip
The format of the input file depends on the extension that you use, a .txt file will be a Tab Separated Values (tsv) file while a .csv file will be a Comma Separated Values (csv) file (please note that this is not a general convention, it is something that was decided by that colleague of yours that wrote the function, or maybe it's a local convention).
Each line of the file is usually composed by three {tab,comma} separated values, i.e., frequency, real part and imaginary part of a complex value.
I said usually composed because the code silently discards all the
lines for which the element count is less than three.
There is something here and there that can be streamlined in the code,
but it's inessential.
Rather, to answer your question re closing the file, change the first part
of the function to
def bbcalfunc(bbfile,nfreqlst):
#define the delimiter
if bbfile.find('.txt')>=0:
delimiter='\t'
elif bbfile.find('.csv')>=0:
delimiter=','
# slurp the file
with file(bbfile,'r') as fid:
fidlines=fid.readlines()
...

Read whole file as text and not line wise in Python? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How to read entire text file as chunk of data or string?
I do not want to read the file line by line instead read entire file as text and find count of certain words. What is the way to do that?
You can use the file read() function "which reads some quantity of data and returns it as a string".
Docs are here.
As for the second question, you might want to use a regex with word boundary anchors:
import re
with open("myfile.txt") as infile:
text = infile.read()
regex = re.compile(r"\bsearchword\b", re.I) # case-insensitive
count = len(regex.findall(text))
Use with and open.read together:
with open("/path/to/file") as file:
text = file.read()
with is a context manager that will auto-close the file for you when done.
You can read it line by line, count the words you are interested in on each line, add the results to the subtotal, and print the total when you are done. Handy if the file you are processing is big enough to cause swapping.

Categories