I do something like this in perl
have no idea how to in python help please.
tia
oldcity
#!/usr/bin/python
i = 0
with open('test-exp-yrs', 'r') as file:
for line in file:
datafile = line.strip(",")
i = i + 1
print '(', i, ')', datafile
( 1 ) expense-16
( 2 ) expense-17
( 3 ) expense-18
ans=raw_input("choose file ? ")
# with open(datafile, 'r') as file:
# do stuff
First, use Python 3.7. End of life for Python 2.7 is in a little over a year. Second, please use more than a one space indent. That's hard to read.
Third, I'm not sure what's not working. The code looks okay, but you could simplify it with enumerate:
with open('test-exp-yrs', 'r') as exp_file:
for line_num, line in enumerate(exp_file):
datafile = line.strip(",")
print '(', line_num, ')', datafile
Oh, and don't use words Python is already using (like 'file') for variables. You could confuse Python.
By your last comment you want to then use the file names you pulled out. Do you want them in another file? For that you would want to open the other file with the 'w' mode, and use that_file.write() to add to it. Simpler would be a list. (
all_files = []; ...; all_files.append(datafile)
).
Thanks for the tips. Using Linux Mint 18.2. Python 2.7 is the default, have just learned 3.5 is
on the system. Will be using it as I have no skill in installing 3.7. My programming background
is from the old school BASIC.
What I wanted to do is say choose the datafile by line_num to use in routine that may be an 'w' mode
routine or a 'r' mode routine. Should have left the # off the last open statement.
If you want to be choosing by line_num, then you want it to be in a list. Accessing specific lines of files is not really supported in Python.
datafiles = []
with open('test-exp-yrs', 'r') as exp_file:
for line_num, line in enumerate(exp_file):
datafile = line.strip(",")
print '(', line_num, ')', datafile
datafiles.append(datafile)
With the above code the files would be shown to the user with the numbers 0, 1, and 2 (Python is zero indexed) and then you could use those numbers to access the datafiles list later (
datafile[1]
).