python - 在 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]
任何人有任何想法来解决这个问题?
解决方案
您正在失去使用上下文管理器的好处,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")
推荐阅读
- c# - 一行程序上的两个 DataGrids 冻结 WPF
- http - 应该使用 Post 或 Put - 如果存在要更新的对象,否则要创建新对象?
- c# - EF Core 上下文不包含添加实体的更改
- postgresql - postgres_1 | ls: 无法访问'/docker-entrypoint-initdb.d/': 不允许操作
- metafor - 使用 metafor 计算效果大小(使用“SMD”):插入组差异的标准差而不是组特定的 SD?
- python - 如何获取 Opennebula XML-RPC api 所需的参数
- c# - C# 8+ 可空引用检查:静态分析能否确定该字段或该字段为非空?
- node.js - 如何在 mac M1 上为 Intel 运行 NodeJS 版本?
- python - 将行拆分为多个,同时保持其他列相同 pandas python
- python - Google Analytics API 报告 startDate 和 endDate 字段