How to concatenate a string from a list into an instance of a long path in Python

Source: Internet
Author: User

Today the internship company assigned a data Processing task. When I connect a string in a list to a long path, I encounter the following problem:

Import ospath_list = [' first_directory ', ' second_directory ', ' file.txt ']print os.path.join (path_list)

After discovering Os.path.join, it is still a list of strings. That's what I was wondering:

[' First_directory ', ' second_directory ', ' file.txt ']

After thinking about it, Os.path.join's input must be one or more str, not a list. The nature of the list of strings is still lists. instruction to interpret a string list as a str, which is equivalent to os.path.join a single str, and, of course, no change at all.

So I changed the code:

Import ospath_list = [' first_directory ', ' second_directory ', ' file.txt ']# print os.path.join (path_list) head = ' for path ' In path_list:    head = os.path.join (head, path) print head

Finally, the string in the list is concatenated into a full long path:

First_directory/second_directory/file.txt
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.