Reputation: 135
The user inputs a string signifying a folder name, then hardcoded file names are added onto that string from a list to create two absolute file paths.
The first file path is ok, but the second adds the filename onto the already added first filename.
files = ["file1.txt", "file2.txt"]
path = str(input("Path: "))
new_paths = []
for file in files:
path += r"\{0}".format(file)
new_paths.append(path)
print(new_paths)
Supposing an user input of:
C:\\Users\User\Desktop\file_folder
The file paths added onto the new_paths
list are:
['C:\\\\Users\\Users\\Desktop\\file_folder\\file1.txt', 'C:\\\\Users\\Users\\Desktop\\file_folder\\file1.txt\\file2.txt']
As opposed to the desired result of:
['C:\\\\Users\\Users\\Desktop\\file_folder\\file1.txt', 'C:\\\\Users\\Users\\Desktop\\file_folder\\file2.txt']
Upvotes: 0
Views: 804
Reputation: 1069
You can do with below mentioned code -
[os.path.join(path, x) for x in files]
# prints you entered path+files
Complete Code:
import argparse
files = ["file1.txt", "file2.txt"]
def create_argparse():
parser = argparse.ArgumentParser()
parser.add_argument('-p','--path',
help='path')
return parser.parse_args()
def main():
args = create_argparse()
path = args.path
print [os.path.join(path, x) for x in files]
if __name__ == '__main__':
sys.exit(main())
Reference:
https://docs.python.org/3/library/argparse.html
Upvotes: 1
Reputation: 1218
You are updating the same variable. Just use it:
for file in files:
new_paths.append(path + r"\{0}".format(file))
print(new_paths)
Upvotes: 1
Reputation: 4882
You are overwriting your variable path
, try
files = ["file1.txt", "file2.txt"]
path = str(input("Path: "))
new_paths = []
for file in files:
file_path = path + r"\{0}".format(file)
new_paths.append(file_path)
print(new_paths)
Upvotes: 2