2013-11-04 75 views
2

我想如何打开读写文件并重新创建文件?

  • 打开并阅读一号文件
  • 打开并阅读第二个选项
  • 复制第二个文件,第一个文件与头
  • 值写入新值到第一档

即第1个文件作为读写模式打开,第2个文件作为读模式。 例如,

1st_file

 CHINESE JAPANESE KOREAN 
CA 0.1  0.1  1.1 
WA 0.2  -0.2  1.3 
OR -0.1  1.1  0.1 
UT 0.3  1.4  -0.9 

2nd_file(无标头)

1.1 
1.3 
-0.1 
1.3 

重新1st_file

 CHINESE JAPANESE KOREAN VIETNAMESE TOTAL 
CA 0.1  0.1  1.1  1.1   2.4 
WA 0.2  -0.2  1.3  1.3   2.6 
OR -0.1  1.1  0.1  -0.1   1.0 
UT 0.3  1.4  -0.9  1.3   2.1 

这里,2nd_file包含有关越南列中的值。

所以,首先要把header,1)VIETNAMESE和2)TOTAL写到1st_file的头部。

然后,将2nd_file的值写入1st_column的相应VIETNAMESE列。

最后,计算1st_column的值并将其写入(例如TOTAL)到1st_column。

我试图用r +模式打开第一个文件,但它没有很好的工作。仅供参考,真正的1st_files拥有大约1亿行和20列。

怎么办?

+1

您需要重写第一个文件,从头开始。 –

+0

只是一个想法 - 使用SQLite代替文本文件可能更好。 – iCodez

+0

如果您正在处理内存中的所有内容,请在读取第一个文件后删除第一个文件并打开一个具有相同名称的新文件。如果您使用的是管道,那么写入第三个文件,一旦完成,它将替换第一个文件。 – Bitwise

回答

1

虽然我同意iCodez,你不应该使用txt文件(也许SQL甚至json)...我会给你一个选择。你可以

file1 = open("example.txt", "r") 
alldatainfile1 = file1.read() 
file1.close() 

file2 = open("example.txt", "r") 
alldatainfile2 = file2.read() 
file2.close() 

现在你与增值经销商合作,而不是文件...

file1 = open("example.txt", "w") 
file1.write(alldatainfile2) 
file1.close() 

请注意,我用“W”的文件中写入(至极将删除所有信息,然后保存新的),但如果你只是想添加信息到文件而不是删除所有你应该使用“a”来附加数据。

最后我建议3个提示:

  • 备份您尝试之前文件的机会,删除重要信息是HIGH。
  • 使用For line in yourfile代码来检查信息是否已经存在,如果是这种情况,请不要复制它,但应该使用json正确完成。
  • 如果这是json会很容易,因为我不会试图给你一个代码来计算一行的总数。

你可以这样做代码:

total = 0 
for line in alldatainfile1: 
    linesplit.split(" ") #3 whitespaces, since you got it that way 
    total = total + line[1] 
print("total of column1: " + str(total)) 
0

你可以试试下面的代码:

FILE_1 = "File1.in" 
FILE_2 = "File2.in" 


def getTableData(file_name): 
    """Retreive the Table Data from 'file_name' and return it as a list()""" 
    file_1 = open(file_name,'r') 
    data = [cols.split() for cols in file_1.read().split('\n')] 
    data[0].insert(0,' ') 
    return data 

def getColumn(file_name): 
    """Retrieve the new Column data from file 'file_name' and return it as a list""" 
    file_2 = open("File2.in", 'r') 
    col = file_2.read().split('\n') 
    return col 

def appendColumn(table, col_name, col): 
    """Append the new Column to the table""" 
    table[0].append(col_name) 
    for x in xrange(len(col)): 
     table[x+1].append(col[x]) 
    return table 

def total(table): 
    """Calculate the Total in the table""" 
    col =[] 
    for i in xrange(len(table)-1): 
     tot = 0.0 
     for j in xrange(len(table[i+1])-1): 
      tot += float(table[i+1][j+1]) 
     col.append(str(tot)) 
    return col 

def writeBack(file_name, table): 
    """Writing the table back to 'file_name'""" 
    fout = open(file_name,"w") 
    for row in table: 
     line = '\t\t'.join(row) 
     fout.write(line + "\n") 


table = appendColumn(getTableData(FILE_1), "VIETNAMESE", getColumn(FILE_2)) 
col = total(table) 
table = appendColumn(table, "TOTAL", col) 
writeBack(FILE_1, table) 

限制:

  • 将在打印的列最终的输出文件将不会是Ind ented。你将不得不玩弄缩进。目前每列由两个分开'\ t'
  • 该代码仅在添加的新列与现有表具有相同行数时才有效。
  • 由于Saelyth已经提到,“w”选项将删除前一个文件并创建一个新文件。所以请确保在试用之前备份数据。

我还假设新的列名不包含在第二个文件中,并且它是从不同的来源接收的。

您正在写回的最终数据表是一个2维矩阵,因此您可以通过简单地执行table[i][j] = "New Data"来编辑(i,j)处的任何条目。

0

我更喜欢使用readlines()来编辑文本文件。这应该做的伎俩:

fileA = open("whatever the file name of first file is", 'r') 
fileALines = fileA.readlines() 
fileA.close() 

fileB = open("whatever the file name of second file is", 'r') 
fileBLines = fileB.readlines() 
fileB.close() 

newLines [] 

newLines[0] = fileALines[0] "VIETNAMESE TOTAL" #I'm not sure how you intend on getting the column header, but you can just insert it here. 

lengthList = [len(header) for header in fileALines[0]] #Used for column widths 

for lineA,lineB in zip(fileALines[1:],fileBLines): 
    itemList = (lineA + lineB).split() 
    itemList.append(str(sum(map(float,itemList)))) 
    for length,item in zip(lenghtList,itemList): 
     newLines.append("{:^{length}}".format(item, length=length)) 
    newLines.append("\n") 

fileC = open("newFile.txt", 'w') 
for line in newLines: 
    fileC.write(line) 
fileC.close() 

使用代码,因为我已经写它会创建一个第三个文件,你可以用它来调试它,如果你有任何问题。

此代码将无法运行:

  • 您的两个文件(不包括标题行)不同行数
  • 你有许多比头
  • 更宽
  • 你和列结束了比头宽
  • 我做了某种愚蠢的错误

我也同意评论和其他答案,文本文件可能不是最好的办法,但它可以做到。希望这可以帮助。

0

如果你想快速和结构化文件使用python的csv库。

import csv 
main_headers = ['state', 'chinese'] 
compound_data = [] 
with open('languages1.csv', 'r') as csv_file: 
    csvreader = csv.DictReader(csv_file) 
    for row in csvreader: 
     compound_data.append(row) 
print(compound_data) 
with open('languages2.csv', 'r') as csv_file: 
    csvreader = csv.DictReader(csv_file) 
    for row in csvreader: 
    compound_data.append(row) 
print(compound_data) 

输出:

[{'state': 'ca', 'chinese': '1.0'}, {'state': 'vt', 'chinese': '2.0'}] 
[{'state': 'ca', 'chinese': '1.0'}, {'state': 'vt', 'chinese': '2.0'}, {'state': 'ca', 'vietnamese': '-0.1'}, {'state': 'vt', 'vietnamese': '1.5'}] 

一旦你有你的数据,你可以改写为csv文件或任何文件你想和应用格式。

相关问题