0

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']
1

3 Answers 3

2

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)
Sign up to request clarification or add additional context in comments.

Comments

1

You are updating the same variable. Just use it:

for file in files:
    new_paths.append(path + r"\{0}".format(file))

print(new_paths)

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.