2012-11-19 53 views
0

我正在编写代码,首先将两个.txt文件读入程序,然后再将这两个.txt文件组合起来,并使用生成的文件执行多个任务。到目前为止,我可以读取文件并将它们分配给变量,并且可以分别打印这两个库,但是我无法弄清楚如何组合这些文件。库或数据库连接

到目前为止,我已经写的代码看起来是这样的:

def ReadAndMerge(): 
    library1=input("Enter 1st filename to read and merge:") 
    library2=input("Enter 2nd filename to read and merge:") 
    namelibrary1= open(library1, 'r') 
    namelibrary2= open(library2, 'r') 
    library1contents=namelibrary1.read() 
    library2contents=namelibrary2.read() 
    print(library1contents) 
    print(library2contents) 
    combinedlibraries=(library1, 'a') 
    #^this didnt work, but it was what i have tried so far 
    combinedlibraries.write(library2) 
    print(combinedlibraries) 
    return 

ReadAndMerge() 

我试着用另一个库附加库,但是Python似乎不喜欢我在做什么。

图书馆1看起来是这样的:

Bud Abbott 51 92.3 
Mary Boyd 52 91.4 
Hillary Clinton 50 82.1 

图书馆2如下所示:

Don Adams 51 90.4 
Jill Carney 53 76.4 
Randy Newman 50 41.2 

有谁知道那些相结合两个库的方法吗?

这样,当我打印组合库中它看起来像

Bud Abbott 51 92.3 
Mary Boyd 52 91.4 
Hillary Clinton 50 82.1 
Don Adams 51 90.4 
Jill Carney 53 76.4 
Randy Newman 50 41.2 

这些都是简单的库 - 如果有人可以的方式有可能超过50名测试更大的库,并结合方向指向了我这两个图书馆,这将是伟大的。

+0

定义“结合图书馆”。 –

+0

基本上把图书馆2的内容放在图书馆1的底部,所以它变成了bud abbot mary boyd hillary clinton don adams jill carney randy newman – spenman

+2

你知道如何打开一个文件进行写入,然后写入一个字符串吗?从您提供给我们的代码示例中,我看起来并不像您(或者至少您忘记键入'open'函数,'combinedlibraries'只是一个元组)。我认为这是你的第一步。之后,实现你想要的是微不足道的。 –

回答

1

正如@PedroRomano评论说的那样,您的问题的一部分是您错过了您所称行不通的行中的open。但是,后面的代码仍然不能正常工作。

我也认为覆盖你的一个起始数据文件可能是一个坏主意。它使你的代码不再是幂等的,所以多次运行它将继续产生副作用。

这里是我,而不是建议:

def ReadAndMerge(): 
    library1filename = input("Enter 1st filename to read and merge:") 
    with open(library1filename, 'r') as library1: 
     library1contents = library1.read() 

    library2filename = input("Enter 2nd filename to read and merge:") 
    with open(library2, 'r') as library2: 
     library2contents = namelibrary2.read() 

    print(library1contents) 
    print(library2contents) 

    combined_contents = library1contents + library2contents # concatenate text 

    print(combined_contents) 

    combined_filename = "combined.txt" # ask user for name here? 
    with open(combined_filename, "w") as combined_file: 
     combined_file.write(combined_contents) 

with声明采取关闭文件一旦你与他们所做的(当你写这一点特别重要)的照顾。此外,它使用合并数据的特定文件名,而不是添加到其中一个源文件。

您可能要考虑的一个问题是,您是否真的需要将组合数据集写入文件。如果您打算重新打开该文件并再次读取数据,则可以跳过中间步骤,直接使用组合数据。如果这是你想要的,你可以用return combined_contents替换上面代码的最后三行。最后,与您的实际问题大部分无关的一点:将您的数据称为“图书馆”是一个不好的主意。这个词在计算机编程中有着非常明确的含义(即:从项目之外加载的软件),并且用它来引用数据是令人困惑的。

+0

谢谢blckknght,您的意见和代码非常有帮助,我应该怎样引用我的数据,好像库因为是不可接受的术语 – spenman

+0

@spenman :嗯,我不确定是否有一个明显的术语。我猜“数据”可能是最好的。或者“数据文件”专门引用文件本身。考虑到上下文,使用库不是太混乱。 – Blckknght