Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Because I need to sort a .txt file with quicksort, I used readlines() to use my function. The problem is that it isn't formatted like before the usage of readlines().
f = open(filename)
array = f.readlines()
Then I used my quicksort function.
How the Input File looks like:
12.01.2020 bcd
05.02.1990 efd
13.04.1992 cba
How it should look like after quicksort:
05.02.1990 efd
13.04.1992 cba
12.01.2020 bcd
but in my code it's looking like this:
'05.02.1990\tefd\n', '13.04.1992\tcba\n', '12.01.2020\tbcd\n'
Any Suggestions how i can correct my usage of readlines()?
This is actually how readlines is used. It generates a list of strings that are found in your text file. As you can see each string is separated by a ,, the tabs are represented as \t and the new line is represented as \n.
You can simply write the array to a file again to get the wanted output.
with open('sorted.txt', 'w') as of:
for s in sorted:
of.write(s)
PS. what you're printing is the content of your output list, this will replace things like tabs and newline characters with their unicode representation. If you loop through your output and print the content, you'll see the output that you want to see.
for s in output:
print(s)
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am trying to automate a task which requires using a specific URL which changes depending on the site location. The site locations are already loaded into a .txt file with no spaces at the beginning nor end of each line. The script runs down the list and changes the variable in the URL to match the line it is currently on then saves it to a file to be used later.
The issue I am having is that the script seems to split the outputted lines nearly every time which breaks my ability to read the lines in the next program.
Sample output:
https://picklepickle.com/api/11/networks/12312313154564654
/fickle/toast/3
https://picklepickle.com/api/11/networks/12312313154564655
/fickle/toast/3
https://picklepickle.com/api/11/networks/12312313154564656/fickle/toast/3
https://picklepickle.com/api/11/networks/12312313154564657/fickle/toast/3
This is a small snippet as the original file has nearly 100 lines in it.
Why does the code output the lines in such a weird way? How do I fix it so that it outputs each URL into one neat line?
raw = open("NetIDs.txt")
networks = raw.readlines()
for line in networks:
for i in line:
f = open("Checker.txt", "a+")
f.write('https://picklepickle.com/api/11/networks/{}/fickle/toast/3\n'.format(line))
f.close()
Maybe try stripping your raw text- readlines() will return \n (newline characters), as well.
...
f.write('https://picklepickle.com/api/11/networks/{}/fickle/toast/3\n'.format(line.strip()))
...
The .strip() will remove characters like \n,\t, and more.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I've got an issue where my regex isn't parsing the output of a file I created:
#!/usr/bin/env python3
import wget, re
url=''
filename=wget.download(url)
with open ('Output.txt', "r") as f:
readlines=f.read()
ret=re.sub("^.*\^", "", readlines)
print(ret)
According to this site, the regex I'm using "^.*\^" is valid for my output. Sample output I'm feeding it is something like this:
1212-2010^readthispart
Where it has a carot for a delimiter. I tried double and single quotes to no avail and I'm not sure if it's an issue elsewhere in my code or what, but the printout does not match what I'm looking for. Ideas?
If I'm reading your question and edits right you're looking to return 'readthispart', correct? If so you need to look into using look-behinds in combination with search. See https://docs.python.org/2/library/re.html. re.search("(?<=\^).*",myinput)
You need to enable multiline mode:
re.sub('^.*\^', '', readlines, flags=re.MULTILINE)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have the following dictionary:
self.info("check_reg_min_max")
self.info(pprint.pformat(check_reg_min_max))
{
'TXH1DH50_DD70_03062018_FULL': [60398572, 60399376],
'TXH2DH50_DD70_03062018_FULL': [5071407, 5071709],
'TXH3DH50_DD70_03062018_FULL': [2822010, 2822116],
'TXH4DH50_DD70_03062018_FULL': [52148625, 52148782],
'TXH5DH50_DD70_03062018_FULL': [6764732, 6764766]
}
What I'm trying to do is write each range of numbers to a file, so I'm doing this:
for filename in check_reg_min_max:
jc.write(range(check_reg_min_max[filename][0], check_reg_min_max[filename][1] + 1))
The error message I keep getting is:
argument 1 must be string or read-only character buffer, not list
My understanding is that range takes two integers, and since it is inclusive, I am adding the +1 to grab the end value.
Any ideas what I am doing wrong?
EDIT: I grabbed the wrong error message. Error message updated.
The write() method expects a string. You can't pass it a range directly, it doesn't know what to do with that. This won't work:
f = open('test.txt', 'w')
f.write(range(1,10))
f.close()
You'd need to do something to convert that range to a string. This is one example of how you might do that, if you wanted a comma-separated list of values:
f = open('test.txt', 'w')
f.write(','.join([str(x) for x in range(1,10)]))
f.close()
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 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()
...