如何打开readwrite文件并重新创建文件?

2024-06-16 14:44:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我想

  • 打开并读取第一个文件
  • 打开并读取第二个文件
  • 将第2个文件的值复制到第1个带头文件
  • 将新值写入第一个文件

也就是说,第一个文件以读写模式打开,第二个文件以读取模式打开。 例如

第一个_文件

     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

第二个_文件(无头)

^{pr2}$

已重新创建第一个_文件

     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

这里,第二个_文件包含关于越南语列的值。在

所以,第一件事是把头,1)越南语和2)TOTAL写入第一个_文件的头。在

然后,将第2个_文件中的值写入第1个_列对应的越南语列。在

最后,计算第1列的值并将其(如总计)写入第1列。在

我试着用r+模式打开第一个文件,但效果不佳。仅供参考,真正的1st_文件有大约1亿行和20列。在

怎么做?在


Tags: or文件模式catotalkorean总计效果
3条回答

您可以尝试以下代码:

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)

限制:

  • 将在最终输出文件中打印的列将不会正确缩进。你得玩缩进。目前,每列由两个'\t'分隔。在
  • 只有当要添加的新列与现有表的行数相同时,代码才有效。在
  • 正如Saelyth已经提到的,“w”选项将删除前一个文件并创建一个新文件。所以在尝试之前一定要备份数据。在

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

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

我更喜欢使用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()

使用我编写的代码将创建第三个文件,如果您有任何问题,可以使用该文件进行调试。在

如果:

  • 两个文件中的行数不同(不包括标题行)
  • 你有一个比页眉宽的数字
  • 您的sum列最终会比标题宽
  • 我犯了一些愚蠢的错误

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

虽然我同意iCodez,你不应该使用txt文件(可能是SQL甚至json)。。。我给你另一个选择。在

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

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

既然你使用的是变量而不是文件你可以。。。在

^{pr2}$

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

最后,我提出三点建议:

  • 在尝试之前备份你的文件,删除重要信息的几率很高。在
  • 使用一个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))

相关问题 更多 >