Pennello Nero Pennello Nero - 6 months ago 12
Python Question

python 2.7: List file in folder and subfolders and write them to file error

I wrote this short code in python 2.7 and it should be listing all files and subfolders into a string. Then it multiply their ascii value by

multi
and concatenate it to
long_string
. Long string should be written to a file but it isn't happening i dont know why. can somebody help me?
There are no error message, the file is just not created.

long_string
is 2 million characters long.

The code:

import os
from random import randint
username = ""
for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
if os.environ.get(name):
username = os.environ.get(name)

long_string = ""

n = 10
multi = 12349790

filelist = os.popen("dir C:\users\%s\desktop /s /b"%(username)).read()
for c in filelist:
number = str(ord(c)*multi)
while len(number) < n:
number = "0"+number
long_string = long_string+number

with open("filelist.txt", "w") as outf:
outf.write(long_string)

a = [long_string[i:i+n] for i in range(0, len(long_string), n)]

long_string2 = ""

for e in a:
long_string2 = long_string2+chr(int(e)/multi)

lista_files = long_string2.split("\n")

print lista_files[:5]

Answer

The code is working fine, that is why it wasn't showing error. You could not see your file because it was somewhere else.

just write the full path when opening filelist.txt and it should work as you want.

you're code should look like this in the end:

import os
from random import randint
username = ""
for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
    if os.environ.get(name):
        username = os.environ.get(name)

long_string = ""

n = 10
multi = 12349790

filelist = os.popen("dir C:\users\%s\desktop\ /s /b"%(username)).read()
for c in filelist:
    number = str(ord(c)*multi)
    while len(number) < n:
        number = "0"+number
    long_string = long_string+number

with open("C:/users/"+username+"/desktop/filelist.txt", "w") as outf:
    outf.write(long_string)

a = [long_string[i:i+n] for i in range(0, len(long_string), n)]

long_string2 = ""

for e in a:
    long_string2 = long_string2+chr(int(e)/multi)

lista_files = long_string2.split("\n")

print lista_files[:5]
Comments