python怎么在中间输入_如何使在中间具有可变输入的路径在python的输入文件中读取...

This should be pretty easy, not sure why I can't get it to work. I am trying to import a ton of .txt files as part of a larger process like so:

path = "C:/Users/A/B/"

with open(path + "*full.txt","r") as f:

contents =f.read()

print(contents)

I am just trying to import all .txt files (there are a ton of them) in this folder path, when I do this I get:

OSError: [Errno 22] Invalid argument:

There are strings in the middle that are different between each file hence the * before the full

it lists the path after argument (for privacy reasons I will leave it out but you get the point) and I know that the path is correct, why is it giving me this error?

解决方案

You can't use * in open(). open() can open only one file with exact name.

You have to get all names in directory and use for-loop to open every file separatelly.

With glob.glob():

import glob

path = "C:/Users/A/B/"

for fullname in glob.glob( path + "*full.txt" ):

with open(fullname, "r") as f:

contents = f.read()

print(contents)

With os.listdir():

import os

path = "C:/Users/A/B/"

for name in os.listdir(path):

if name.endswith("full.txt"):

fullname = os.path.join(path, name):

with open(fullname, "r") as f:

contents = f.read()

print(contents)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值