首页 > 解决方案 > 在 Python 中将文件路径作为变量

问题描述

我对 Python 非常陌生,我正在尝试获取一些代码来将文本文件连接成一个!

我有以下代码:

Checkpoint = open("/Users/owenmurray/Desktop/vocab/Custom_Vocab_Split_by_Brand_Checkpoint.txt", "r")
eightbyeight = open("/Users/owenmurray/Desktop/vocab/Custom_Vocab_Split_by_Brand_8x8.txt", "r")
AmazonAWS = open("/Users/owenmurray/Desktop/vocab/Custom_Vocab_Split_by_Brand_AmazonAWS.txt", "r")
Common_Tech_Terms = open("/Users/owenmurray/Desktop/vocab/Custom_Vocab_Split_by_Brand_Common_Tech_Terms.txt", "r")

import sys

filenames = ['Common_Tech_Terms', 'eightbyeight', 'AmazonAWS', 'Checkpoint']
with open('output_file2.txt', 'w+') as outfile:
    for fname in filenames:
        with open(fname) as infile:
            for line in infile:
                outfile.write(line + "\n")

我收到以下错误:

Traceback (most recent call last):
  File "/Users/owenmurray/Desktop/Combining Files", line 60, in <module>
    with open(fname) as infile:
IOError: [Errno 2] No such file or directory: 'Common_Tech_Terms'
[Finished in 0.1s with exit code 1]
[shell_cmd: python -u "/Users/owenmurray/Desktop/Combining Files"]
[dir: /Users/owenmurray/Desktop]

任何人有任何想法来解决这个问题?

标签: pythonpython-2.7

解决方案


您正在失去使用上下文管理器的好处,open当您需要文件内容时调用:

Checkpoint = "/Users/owenmurray/Desktop/vocab/Custom_Vocab_Split_by_Brand_Checkpoint.txt"
eightbyeight = "/Users/owenmurray/Desktop/vocab/Custom_Vocab_Split_by_Brand_8x8.txt"
AmazonAWS = "/Users/owenmurray/Desktop/vocab/Custom_Vocab_Split_by_Brand_AmazonAWS.txt"
Common_Tech_Terms = "/Users/owenmurray/Desktop/vocab/Custom_Vocab_Split_by_Brand_Common_Tech_Terms.txt"

filenames = [Common_Tech_Terms, eightbyeight, AmazonAWS, Checkpoint]
with open('output_file2.txt', 'w+') as outfile:
    for fname in filenames:
        with open(fname, "r") as infile:
            for line in infile:
                outfile.write(line + "\n")

推荐阅读