如何使用open方法在python中读取文本文件

时间:2017-12-05 07:16:03

标签: python python-3.x python-2.7

我有一个文本文件mycontacts.txt

enter image description here

我需要阅读此文件的内容。 位置路径为:C:\ Users \ myusername \ Documents \ SQL_NeedToKnow \ Python 我在这里使用示例:https://medium.freecodecamp.org/send-emails-using-code-4fcea9df63f

# Function to read the contacts from a given contact file and return a
# list of names and email addresses
def get_contacts(filename):
    names = []
    emails = []
    with open(filename, mode='r', encoding='utf-8') as contacts_file:
        for a_contact in contacts_file:
            names.append(a_contact.split()[0])
            emails.append(a_contact.split()[1])
    return names, emails

所以对我来说,似乎我需要先更改目录。 为此,我使用os.chdir方法。 不知道我应该把它放在哪里,但我甚至没有错误。 我正在使用Jupyter。 我想这样做:

# Function to read the contacts from a given contact file and return a
# list of names and email addresses
import os
os.chdir(r'''C:\Users\oserdyuk\Documents\SQL_NeedToKnow\Python''')
def get_contacts(filename):
    names = []
    emails = []
    with open("mycontacts.txt", mode='r', encoding='utf-8') as contacts_file:
        for a_contact in contacts_file:
            names.append(a_contact.split()[0])
            emails.append(a_contact.split()[1])
    return names, emails

我也尝试过以完整路径打开:

# Function to read the contacts from a given contact file and return a
# list of names and email addresses
import os
#os.chdir(r'''C:\Users\oserdyuk\Documents\SQL_NeedToKnow\Python''')
def get_contacts(filename):
    names = []
    emails = []
    with open(r'''C:\Users\oserdyuk\Documents\SQL_NeedToKnow\Python''', mode='r', encoding='utf-8') as contacts_file:
        for a_contact in contacts_file:
            names.append(a_contact.split()[0])
            emails.append(a_contact.split()[1])
    return names, emails

2 个答案:

答案 0 :(得分:2)

使用您的代码,我假设您正在尝试从给定文件中的条目中的两个列表中获取姓名和电子邮件。

因此,在代码中进行一些编辑后,请尝试以下操作:

def get_contacts(filename):
    names = []
    emails = []
    with open(filename, 'r') as contacts_file:
        for row in contacts_file.readlines():  # this is what missing
            name, email = row.split(",")  # split will be with "," delimiter
            names.append(name)
            emails.append(email)
    return names, emails

答案 1 :(得分:0)

在该函数中,您尝试打开实际文件,而不是使用函数参数。

重写功能:

def get_contacts(filename):    
    names = []
    emails = []

    with open(filename) as contacts_file:
        for a_contact in contacts_file.readlines():
            name, email = a_contact.strip().split(', ')
            names.append(name)
            emails.append(email)

    return names, emails

# When you call the function, pass the file path as an argument
print(get_contacts('test.txt'))

(['Abc', 'Xyz'], ['abc@email.com', 'xyz@email.com'])
>>>