Home > Blockchain >  python - open files and other methods for file
python - open files and other methods for file

Time:10-26

im trying to code a function length_n(file_name, n) where it returns the list of words within file_name (a txt file) that has a length of n. file_name will be the name of the file containing the list of words. for some reason, when I test my codes, the "open" operation does not successfully open my text file. Does anyone know why? Also, did I use the methods .read and .split correctly? thank you so much!

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

CodePudding user response:

You can't do this:

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

Python tries to find 'file_name' file, but I'm pretty sure it does not exist.

Here's solution:

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

CodePudding user response:

I modified your code like that,

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

When we use with open(f'file_name','r') as file it simply close file after your program is close.

  • Related