import os
s = os.listdir("qwe")
f = open("asd.txt", "w")
for i in range(0, 100):
try:
f.writelines(s[i] + ":" + "\n")
f.writelines(os.listdir("qwe\ ".strip() + s[i] + "\Wallets"))
f.writelines("\n" + "\n")
except:
continue
It prints data like this:
dsadasda:
ada.txtli.pysda.txt
elele:
erti:
file.txt
jhgjghjgh:
new.txtpy.py
lolo:
sdada:
If there are lots of things in wallet it prints them together, how can i space between them?
you may write your code as this way
import os
s = os.listdir("qwe")
try:
with open("asd.txt", "a") as f: # opening file once
for i in range(0, 100):
f.writelines(s[i] + ":" + "\n")
print(s[i] + ":" + "\n")
f.writelines(os.listdir("qwe\ ".strip() + s[i] + "\Wallets"))
print(os.listdir("qwe\ ".strip() + s[i] + "\Wallets"))
f.writelines("\n" + "\n")
except:
pass
this is happening because you open the file for each loop so it doesn't write anything in your file
,
another thing that you are opening file in writing mode which means that it will erase the content of the file and replace it with the new one
Related
I am made a file where i can reference functions and i thought that it would be fun to make a program to add text to the file, and when i try to open the file, it doesn't show any errors, but when i go and check the file there's nothing there.
My code:
ime_funk = input("Ime funkcije: ")
x = 0
funk = ""
while True:
vseb_funk = input("Kopiraj eno, pa po eno vrstico funkcije, ko si končal napiši končano: ")
if vseb_funk == "končano":
break
else:
funk += "\n "+vseb_funk
mark = open("test.txt", "a")
mark.write("\n" + ime_funk + "\n" + funk)
Don't pay attention to the variable names and strings, as that's not important.
Also I am using replit if that's important.
I have no idea why it doesn't work.
i have tried mark = open("test.txt", "w") but same story.
you need to add this line to your code
mark.close()
or what you can do I replace this part of the code
mark = open("test.txt", "a")
mark.write("\n" + ime_funk + "\n" + funk)
with this code:
with open("test.txt", "a") as mark:
mark.write("\n" + ime_funk + "\n" + funk)
A file write in python does not happen untill you call file.flush(). This is usually called automatically when you close the file but in your example you are never closing the file. Try:
ime_funk = input("Ime funkcije: ")
x = 0
funk = ""
while True:
vseb_funk = input("Kopiraj eno, pa po eno vrstico funkcije, ko si končal napiši končano: ")
if vseb_funk == "končano":
break
else:
funk += "\n "+vseb_funk
mark = open("test.txt", "a")
mark.write("\n" + ime_funk + "\n" + funk)
mark.close()
or even better try using the with statement:
with open("test.txt", "a") as mark:
mark.write("\n" + ime_funk + "\n" + funk)
this way close() is called automatically
I added my code below. The output is always an empty file.
Fasta_1 = ">ABC123\n ATCGTACGATCGATCGATCGCTAGACGTATCG"
Fasta_2 = ">DEF456\n actgatcgacgatcgatcgatcgacgact"
Fasta_3 = ">JIH789\n ACTGAC-ACTGT--ACTGTA----CATGTG"
output = open("sequence.fasta", "w")
output.write = (Fasta_1 + '\n' + Fasta_2 + '\n' + Fasta_3)
output.close()
Your problem is output.write is not a property, it is function. So, it should be called this way:
Fasta_1 = ">ABC123\n ATCGTACGATCGATCGATCGCTAGACGTATCG"
Fasta_2 = ">DEF456\n actgatcgacgatcgatcgatcgacgact"
Fasta_3 = ">JIH789\n ACTGAC-ACTGT--ACTGTA----CATGTG"
output = open("sequence.fasta", "w")
output.write(Fasta_1 + '\n' + Fasta_2 + '\n' + Fasta_3) # < !!!!
output.close()
I am trying to loop over the lines in a file and create multiple directories. My script is working only for the first line of list in a file. Here is my script. I have attached image of list as well. That is for both list_bottom.dat and list_top.dat.
import os
f = open("list_top.dat", "r")
g = open("list_bottom.dat", "r")
for lines in f:
m_top = lines.split()[0]
m_bot = lines.split()[0]
os.mkdir(m_top)
os.chdir(m_top)
for lines in g:
print(lines)
m_bot = lines.split()[0]
print(m_bot)
os.mkdir(m_top + "_" + m_bot)
os.chdir(m_top + "_" + m_bot)
for angle in range(5):
os.mkdir(m_top + "_" + "m_bot" + "_angle_" + str(angle))
os.chdir(m_top + "_" + "m_bot" + "_angle_" + str(angle))
os.chdir("../")
os.chdir("../")
os.chdir("../")
os.chdir("../")
you are trying to read from a file pointer, not from its content. you should do this instead
with open("file.txt") as f:
lines = f.readlines()
for line in lines:
do_stuff()
(for readability i don't post this as a comment, but that's a comment)
Say I have a file with 10GB that has 20,000 lines filled with the digits of pi.
123123
12312312
123123
123123
12312312
123123
How do I extract lines 10,000 to 20,000 using the unix command sed -n?
I'd like for each line with a newline character to export to a file using the code below.
So far, I have the following:
com = "sed -n \' " + str(window[0]) + "," + str(window[1]) + "p\' " + "sample.txt" + ">" + "output.txt"
os.system(com)
but it is throwing concatenation errors.
How should I phrase the command sed -n for Python in the program below?
inputFileName = "sample.txt"
import itertools
import linecache
def sliding_window(window_size, step_size, last_window_start):
for i in xrange(0, last_window_start, step_size):
yield (i, i + window_size)
yield (last_window_start, total_pi_digits)
def PiCrop(window_size, step_size):
f = open(inputFileName, 'r')
first_line = f.readline().split()
total_pi_digits = int(first_line[0])
last_window_start = total_pi_digits-(total_pi_digits%window_size)
lastcounter = (total_pi_digits//window_size)*(window_size/step_size)
flags = [False for i in range(lastcounter)]
first_line[0] = str(window_size)
second_line = f.readline().split()
offset = int(round(float(second_line[0].strip('\n'))))
first_line = " ".join(first_line)
f. close()
with open(inputFileName, 'r') as f:
header = f.readline()
for counter, window in enumerate(sliding_window(window_size,step_size,last_window_start)):
with open('PiCrop_{}.txt'.format(counter), 'w') as output:
if (flags[counter] == False):
flags[counter] = True
headerline = float(linecache.getline(inputFileName, window[1]+1)) - offset
output.write(str(window_size) + " " + str("{0:.4f}".format(headerline)) + " " + 'L' + '\n')
com = "sed -n \' " + str(window[0]) + "," + str(window[1]) + "p\' " + "sample.txt" + ">" + "output.txt"
os.system(com)
PiCrop(1000,500)
You can yield each line from the file:
def lines(filename):
with open(filename) as f:
for line in f:
yield line
And you can slice the sequence using islice:
from itertools import islice
with open('PiCrop.txt', 'w') as output:
for line in islice(lines('sample.txt'), 10000, 20001):
output.write(line)
I successfully simplified a python module that imports data from a spectrometer
(I'm a total beginner, somebody else wrote the model of the code for me...)
I only have one problem: half of the output data (in a .csv file) is surrounded by brackets: []
I would like the file to contain a structure like this:
name, wavelength, measurement
i.e
a,400,0.34
a,410,0.65
...
but what I get is:
a,400,[0.34]
a,410,[0.65]
...
Is there any simple fix for this?
Is it because measurement is a string?
Thank you
import serial # requires pyserial library
ser = serial.Serial(0)
ofile = file( 'spectral_data.csv', 'ab')
while True:
name = raw_input("Pigment name [Q to finish]: ")
if name == "Q":
print "bye bye!"
ofile.close()
break
first = True
while True:
line = ser.readline()
if first:
print " Data incoming..."
first = False
split = line.split()
if 10 <= len(split):
try:
wavelength = int(split[0])
measurement = [float(split[i]) for i in [6]]
ofile.write(str(name) + "," + str(wavelength) + "," + str(measurement) + '\n')
except ValueError:
pass # handles the table heading
if line[:3] == "110":
break
print " Data gathered."
ofile.write('\n')
do this:
measurement = [float(split[i]) for i in [6]]
ofile.write(str(name) + "," + str(wavelength) + "," + ",".join(measurement) + '\n')
OR
ofile.write(str(name) + "," + str(wavelength) + "," + split[6] + '\n')