Reputation: 13
The idea is simple: there is a directory with 2 or more files *.txt. My script should look in the directory and get filenames in order to copy them (if they exist) over the network. As a Python newbie, I am facing problems which cannot resolve so far. My code:
files = os.listdir('c:\\Python34\\');
for f in files:
if f.endswith(".txt"):
print(f)
This example returns 3 files:
LICENSE.txt
NEWS.txt
README.txt
Now I need to use every filename in order to do a SCP. The problem is that when I try to get the first filename with:
print(f[0])
I am receiving just the first letters from each file in the list:
L
N
R
How to add filenames to an array in order to use them later as a array elements?
Upvotes: 1
Views: 249
Reputation: 99
You can also try using the EXTEND method. So you say:
x = []
for f in files:
if f endswith(".txt"):
x.extend([f])
so it would be "adding" to the end of the list the file in which f is on.
Upvotes: 1
Reputation: 142206
If you want a list
of matching files names, then instead of using os.listdir
and filtering, use glob.glob
with a suitable pattern.
import glob
files = glob.glob('C:\\python34\\*.txt')
Then you can access files[0]
etc...
Upvotes: 0
Reputation: 11060
The array of files is files
. In the loop, f
is a single file name (a string) so f[x]
gets the xth character of a filename. Do files[0]
instead of f[0]
.
Upvotes: 0