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()
...
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I have a data csv file with first few rows are storing information.
The format is like this:
info1, aa
info2, bb
info3, cc
col1, col2, col3
x1, y1, z1
x2, y2, z2
If I use numpy.genfromtxt(), it will show error due to different columns between first three lines, and the rest.
I can use numpy.genfromtxt(skip_header=3) to read the data, and numpy.genfromtxt(skip_footer= ) to read the information.
I wonder if there is a better way to do this?
When I need a solution like this and I don't know the number of lines in the header block beforehand, I read only the first column. Then I look in that column for the blank lines, which tells me where the section boundaries are. Finally I read the full data by passing the appropriate number of lines to skip and read each time.
If the file is large and I care about efficiency, I open() it once and pass that file handle to genfromtxt() with the number of lines in each section, which means the whole operation takes just two passes over the file (because the file handle remains open, all we need to do is call readline() on it to skip blank lines between sections).
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.
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)
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.
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 8 years ago.
Improve this question
Suppose that I would like my python program to accept 2 positional arguments:
1. The path to an input file
2.The path to a word dictionary, which is also a txt file.
Can anyone teach me how to go about doing that?
import sys
print('Name of the script: {0}'.format(sys.argv[0]))
if len(sys.argv) == 3:
inputfile_path = sys.argv[1]
dictionary_path = sys.argv[2]
print('First parameter: {0}'.format(inputfile_path))
print('Second parameter: {0}'.format(dictionary_path))
https://docs.python.org/2/library/sys.html
Your question is a bit vague so I'm just going to answer what I think you meant.
I'll assume that you have a function as such:
def function(string1, string2):
''' string 1 and string2 are paths to an input file and a dictionary respectively'''
Now in general to read a file you use:
file1 = open(string1,'r')
# After opening the file you loop over lines to do what you need to.
for line in file:
# Do what you need to
I'm not sure what you want to do with the input file so I'm going to leave it at that.
To load a dictionary from a string we use the eval() function. It actually runs a string. Now each line in the dictionary stored as a text file is a string so all you have to do is loop through the entire file (using the for line in file method from before) and run eval to get back a dictionary.
For example try this simple code:
#assume string2 is what you get back from the looping
string2 = str({'jack': 4098, 'sape': 4139})
dic = eval(string2)
print dic
Hopefully I've pointed you in the right direction. Since I'm not sure what exactly you need to do, I can't really help you more.