Reputation: 1702
I created the following simple python script that runs on linux - python ver 2.X
#!/usr/bin/python
def GetListfiles():
LS = (commands.getstatusoutput(" ls "))
return LS
AA = GetListfiles()
for filename in AA:
print "------------"
print filename
after I run my script I get this output:
file.txt
file1.txt
file2.txt
why I not get output as like this?
------------
file.txt
------------
file1.txt
------------
file2.txt
what I need to change in my code ?
Upvotes: 1
Views: 60
Reputation: 2592
You need to split the file names.
commands.getstatusoutput(" ls ")
returns a tuple - 2 items that looks like this:
(0, 'filename.txt\nfilename1.txt\nfilename2.txt')
so it is prinitng -----
then 0
, -----
again and then the string filename.txt\nfilename1.txt\nfilename2.txt
which appears as this:
--------------
0
--------------
filename.txt
filename1.txt
filename2.txt
So to get one line between each, do this:
def GetListfiles():
LS = (commands.getstatusoutput(" ls "))
return LS
AA = GetListfiles()
AA = AA[1].split('\n')
for filename in AA:
print "---------------"
print filename
To check the file name includes the text txt
, do this:
for filename in AA:
print "---------------"
if "txt" in filename:
print filename
Upvotes: 3
Reputation: 12022
This will do what you're intending in pure Python:
import glob
filenames = glob.glob('*')
for filename in filenames:
print "------------"
print filename
Upvotes: 1