简体   繁体   中英

Python - Reading first two lines from txt files

I'm trying to create a program that reads the path given by the user and then reads the first two lines of txt files that exists at that specific path.

Problem is that I'm given this error:

"TypeError: coercing to Unicode: need string or buffer, builtin_function_or_metho d found"

I don't understand why?

#!/usr/bin/python

import glob, os
import sys

#Check to see that path was privided
if len(sys.argv) < 2:
    print "Please provide a path"

#Find files in path given
os.chdir(dir)
#Chose the ones with txt extension
for file in glob.glob("*.txt"):
    try:
        #Read and output first two lines of txt file
        f = open(file)
        lines = f.readlines()
        print lines[1]
        print lines[2]
        fh.close()

        #Catch exception errors
    except IOError:
        print "Failed to read " + file

You seem to be mistaking the built-in dir to mean a directory name; no it's not.

You should be passing a directory path to os.chdir and not dir :

os.chdir('/some/directory/path')

BTW, you don't need to read the entire file into memory to get your two lines, you can simply call next on the file object:

with open(file) as f:
    line1, line2 = next(f), next(f)

Also, if there is no path in the input, you should exit after printing the error message, otherwise you will get an IndexError for

os.chdir(sys.argv[1])

And if the file has only one line, the second next(f) will give a StopIteration exception, which should be either catched, or you can use next(f, "") for the second line, this will default to an empty string in case the end of file is reached.

EDIT: I was entering the wrong path. :(

Ok, so I have edited the code now and i get no errors. Problem now is that if i run it with python readfiles.py /home/ nothing happens?

#!/usr/bin/python

import glob, os
import sys

#Check to see that path was privided
if len(sys.argv) < 2:
    print "Please provide a path"
    sys.exit()

#Find files in path given

os.chdir(sys.argv[1])

#Chose the ones with txt extension

for file in glob.glob("*.txt"):
    try:

#Read and output first two lines of txt file
        with open(file) as f:
        line1, line2 = next(f), next(f, "")
        print line1 + " " + line2

    #Catch exception errors
except IOError:
        print "Failed to read " + file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM