I have this code that works:
print((tabulate(email_list, showindex=False, tablefmt = 'plain')), file=open(output + '\\' + "np.txt", "w"))
but when I open the file, the email addresses look like this:
b e r o s u n a # g m a i l . c o m
I have tried all the tablefmts and none work, I need it as plain text with no index and no headers left aligned because then I copy them and use it in another process.
Thanks I just changed it completely:
emails = email_list.tolist()
textfile = open(output + '\\' + "np.txt", "w")
for element in emails:
textfile.write(element + "\n")
textfile.close()
os.startfile(output + '\\' + 'np.txt')
Related
I'm trying to write certain measurements to an output file in python3, but the output file only reflects the first 10 lines
I'm using the following code to write to the file:
f = open("measurements.txt", "w")
for infile in glob.glob("./WAVs/*"):
#do some stuff with the input file
f.write(outfile.removesuffix(".wav") + "\t" + str(oldSIL) + "\t" +
str(oldSPL) + "\t" + str(oldLoud) + "\t" + str(newLoud) + "\t"+
infile.removesuffix(".wav") + "\n")
f.close()
Looking at measurements.txt I find that only the first 10 lines of the expected output have been written.
If I try to print the same lines instead of writing to a file using
print(outfile.removesuffix(".wav") + "\t" + str(oldSIL) + "\t" + str("oldSPL") + "\t" + str(oldLoud) + "\t" + str(newLoud) + "\t"+ infile.removesuffix(".wav") + "\n")
It correctly prints every single line up to the final index. I'm a little lost as to why this might be the case.
I want a text file that has every variation of xxxxx-xxxxx (x is a number)
so I want to create a text file that goes
00000-00000
00000-00001
00000-00002
00000-00003
etc...
how can I do that with python?
The trick is to use .zfill(n) if you want to append "n" zeros before some integers. So, if you have i = 1 but you want to print it like 00001, you can you the following code:
print(str(i).zfill(5))
And as to your question, the solution is:
with open("output.txt", "a") as f:
for i in range(100000):
for j in range(100000):
my_str = str(i).zfill(5) + "-" + str(j).zfill(5) + "\n"
f.write(my_str)
f.close()
Note: This will take a while to complete.
You can do it using a nested loop like this:
pattern = '00000-00000'
stack = []
for i in range(100000):
for j in range(100000):
num = pattern[:5-len(str(i))]+str(i) + pattern[5] + pattern[6:-len(str(j))]+str(j)
stack.append(num)
***Just don't run this code. It will break your computer.
Try this.
lst = []
s = '0000000000'
for a in range(10000):
l = list(s + str(a))[-10:]
l.insert(4,'-')
lst.append(''.join(l)+'\n')
with open('name.txt','w') as file:
file.writelines(lst)
so -----2-----3----5----2----3----- would become -----4-----5----7----4----5-----
if the constant was 2 and etc. for every individual line in the text file.
This would involve splitting recognising numbers in between strings and adding a constant to them e.g ---15--- becomes ---17--- not ---35---.
(basically getting a guitar tab and adding a constant to every fret number)
Thanks. Realised this started out vague and confusing so sorry about that.
lets say the file is:
-2--3--5---7--1/n-6---3--5-1---5
and im adding 2, it should become:
-4--5--7---9--3/n-8---5--7-3---7
Change the filename to something relevant and this code will work. Anything below new_string needs to be change for what you need, eg writing to a file.
def addXToAllNum(int: delta, str: line):
values = [x for x in s.split('-') if x.isdigit()]
values = [str(int(x) + delta) for x in values]
return '--'.join(values)
new_string = '' # change this section to save to new file
for line in open('tabfile.txt', 'r'):
new_string += addXToAllNum(delta, line) + '\n'
## general principle
s = '-4--5--7---9--3 -8---5--7-3---7'
addXToAllNum(2, s) #6--7--9--11--10--7--9--5--9
This takes all numbers and increments by the shift regardless of the type of separating characters.
import re
shift = 2
numStr = "---1----9---15---"
print("Input: " + numStr)
resStr = ""
m = re.search("[0-9]+", numStr)
while (m):
resStr += numStr[:m.start(0)]
resStr += str(int(m.group(0)) + shift)
numStr = numStr[m.end(0):]
m = re.search("[0-9]+", numStr)
resStr += numStr
print("Result:" + resStr)
Hi You Can use that to betwine every line in text file add -
rt = ''
f = open('a.txt','r')
app = f.readlines()
for i in app:
rt+=str(i)+'-'
print " ".join(rt.split())
import re
c = 2 # in this example, the increment constant value is 2
with open ('<your file path here>', 'r+') as file:
new_content = re.sub (r'\d+', lambda m : str (int (m.group (0)) + c), file.read ())
file.seek (0)
file.write (new_content)
I have 15 .csv files with the following formats:
**File 1**
MYC
RASSF1
DAPK1
MDM2
TP53
E2F1
...
**File 2**
K06227
C00187
GLI1
PTCH1
BMP2
TP53
...
I would like to create a loop that runs through each of the 15 files and compares 2 at each time, creating unique pairs. So, File 1 and File 2 would be compared with each other giving an output telling me how many matches it found and what they were. So in the above example, the output would be:
1 match and TP53
The loops would be used to compare all the files against each other so 1,3 (File 1 against File 3), 1,4 and so on.
f1 = set(open(str(cancers[1]) + '.csv', 'r'))
f2 = set(open(str(cancers[2]) + '.csv', 'r'))
f3 = open(str(cancers[1]) + '_vs_' + str(cancers[2]) + '.txt', 'wb').writelines(f1 & f2)
The above works but I'm having a hard time creating the looping portion.
In order not to compare the same file, and make the code flexible to the number of cancers, I would code like this. I assume cancer is a list.
# example list of cancers
cancers = ['BRCA', 'BLCA', 'HNSC']
fout = open('match.csv', 'w')
for i in range(len(cancers)):
for j in range(len(cancers)):
if j > i:
# if there are string elements in cancers,
# then it doesn't need 'str(cancers[i])'
f1 = [x.strip() for x in set(open(cancers[i] + '.csv', 'r'))]
f2 = [x.strip() for x in set(open(cancers[j] + '.csv', 'r'))]
match = list(set(f1) & set(f2))
# I use ; to separate matched genes to make excel able to read
fout.write('{}_vs_{},{} matches,{}\n'.format(
cancers[i], cancers[j], len(match), ';'.join(match)))
fout.close()
Results
BRCA_vs_BLCA,1 matches,TP53
BRCA_vs_HNSC,6 matches,TP53;BMP2;GLI1;C00187;PTCH1;K06227
BLCA_vs_HNSC,1 matches,TP53
To loop through all pairs up to 15, something like this can do it:
for i in range(1, 15):
for j in range(i+1, 16):
f1 = set(open(str(cancers[i]) + '.csv', 'r'))
f2 = set(open(str(cancers[j]) + '.csv', 'r'))
f3 = open(str(cancers[i]) + '_vs_' + str(cancers[j]) + '.txt',
'wb').writelines(f1 & f2)
I have a Python file with a few hundred lines of code. The longest line is 146 characters. How would I put # in column 200 down the whole file within Sublime Text? Preferably with one or two Sublime Text commands?
1 200
print("Hello world!") #
You can try something like this. Note that this writes to a new file: let me know if you want me to modify so that it overwrites the existing file:
data = []
with open('data.txt', 'r') as f:
data = [line[:-1] + ' ' * (200 - len(line)) + '#\n' for line in f]
with open('new_data.txt', 'w') as f:
f.writelines(data)
Note that this will have just append the "#" at the end of the line (regardless of column number) if the line length >= 200.
Here's a possible solution:
N = 200
output = [l.rstrip() for l in f]
output = ["{0}#{1}".format(
l[:len(l[:N])] + ' ' * (N - len(l[:N])), l[N:]) for l in output]
print("\n".join(output))
Or written differently:
N = 200
output = []
for l in f:
l = l.rstrip()
l1 = len(l[:N])
output.append("{0}#{1}".format(l[:l1] + ' ' * (N - l1), l[N:]))
print("\n".join(output))