【问题标题】:python - open files and other methods for filepython - 打开文件和文件的其他方法
【发布时间】:2021-10-26 03:06:10
【问题描述】:

我试图编写一个函数length_n(file_name, n),它返回file_name(一个txt文件)中长度为n的单词列表。 file_name 将是包含单词列表的文件的名称。出于某种原因,当我测试我的代码时,open 操作没有成功打开我的文本文件。有谁知道为什么?另外,我是否正确使用了.read.split 方法?非常感谢!

def length_n(file_name,n):
    #the list of words will be called 
    l1=[]
    #the list of words with the length of n will be called
    l2=[]
    file=open('file_name','r')
    #the individual lines are
    lines=file.read()
    #split the content into words
    l1=lines.split("")
    length=len(l1)
    for i in range (0,length):
        l=len(l1[i])
        if l==n:
            l2.append(l1[i])
            
    return l2

【问题讨论】:

  • “打开”操作没有成功打开我的文本文件是什么意思?您收到错误消息吗?如果有,是什么?

标签: python file methods


【解决方案1】:

你不能这样做:

file=open('file_name','r')

Python 尝试查找“file_name”文件,但我很确定它不存在。

解决办法:

file=open(f'{file_name}.txt','r') # you can remove '.txt' if you don't need it

#OR

file=open(file_name,'r') # or simply just this

【讨论】:

  • 开始你的问题会更准确,解释open('file_name', 'r') 没有做OP认为它做的事情或有他们忽略的错字。说他们根本做不到是不正确的。
  • 好吧,我想我不应该说'你不能这样做',但我已经在第一个代码下面写了解释。
  • 嗨,非常感谢您的回答。我尝试了 file=open('{file_name}.txt', 'r,') 并使用 length_n(cool,4) 对其进行了测试(我的文件夹中有一个名为 cool.txt 的文件),它给出了错误“没有这样的文件或目录:'{file_name}.txt'"。看来它正在将 file_name 作为文件的名称 hmmm
  • @needhelpwithmathandcs,别忘了小f
  • 我也试过 file=open(file_name, 'r') 并且它说:“预期的 str、字节或 os.PathLike 对象,而不是 _io.TextIOWrapper”
【解决方案2】:

我这样修改了你的代码,

def length_n(file_name,n):
   #the list of words will be called 
    l1=[]
    #the list of words with the length of n will be called
    l2=[]
    with open(f'{file_name}','r') as file: # We can't use file = because it doesn't read it is a parameter of length_n. Then we should use formatter or file = open(file_name,'r').
          lines=file.read()
          l1=lines.split("")
          length=len(l1)
          for i in range (0,length):
              l=len(l1[i])
              if l==n:
                 l2.append(l1[i])
        
     return l2

当我们使用 with open(f'file_name','r') 作为文件时,它只是在您的程序关闭后关闭文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-22
    • 1970-01-01
    • 2016-08-17
    • 2018-08-24
    • 2019-04-25
    • 1970-01-01
    • 2010-10-30
    • 1970-01-01
    相关资源
    最近更新 更多