2013-11-04 74 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文件或任何文件你想和應用格式。

相關問題