繁体   English   中英

Python 2.7,将用户输入写入新的输出文件

[英]Python 2.7, writing user input to a new output file

我正在尝试获取包含多个条目的文件并将其写入新文件。 新文件应在单独的列表中包含剥离和逗号分隔的数据。 完成后,我想使用第3行(观察到)和第4行(预期)来计算z得分。 我正在使用的z得分公式是Zi =(Observed i-Expected i)/ sqrt(Expected i)。然后我想将Zscores添加到输入文件中的数据列表中,这是我遇到的麻烦。 我正在使用output_file = open(outpath,“ w”),但没有任何内容写入输出文件。

输入文件示例数据:Ashe,1853282.679,1673876.66,1,2 Alleghany,1963178.059,1695301.229,0,1 Surry,2092564.258,1666785.835,5,6 Currituck,3464227.016,1699924.786,1,1 Northampton,3056933.525,1688585.272,9,3 Hertford ,3180151.244,1670897.027,7,3卡姆登,3403469.566,1694894.58,0,1盖茨,3264377.534,1704496.938,0,1沃伦,2851154.003,1672865.891,4,2

我的代码:

   import os
from math import sqrt
def calculateZscore(inpath,outpath):
    "Z score calc"
    input_file = open(inpath,"r")
    lines = input_file.readlines()
    output_file = open(outpath,"w")


    county = []
    x_coor = []
    y_coor = []
    observed = []
    expected = []
    score = 0
    result = 0



    for line in lines:
        row = line.split(',')
        county.append(row[0].strip())
        x_coor.append(row[1].strip())
        y_coor.append(row[2].strip())
        observed.append(int(row[3].strip()))
        expected.append(int (row[4].strip()))

    o = observed
    e = expected
    length_o = len(o)
    length_e = len(e)
    score = 0
    for i in range(length_o):
        score += (o[i] - e[i])
        result += (score/(sqrt(e[i])))







def main():
    "collects data for code "
workingDirec = raw_input("What is the working directory?")
original_file = raw_input("The input filename is?")
full_original = os.path.join(workingDirec,original_file)
chi_square = raw_input("The name of the chi-squared stats table file is?")
full_chi_square = os.path.join(workingDirec,chi_square)
output_file = raw_input ("What is the output filename?")
full_output = os.path.join(workingDirec,output_file)

calculateZscore(full_original,full_output)

任何指导将不胜感激

问题是您的代码中的访问模式input_file = open(inpath,"r")您以只读模式打开文件,您也需要授予写权限。

r打开一个文件以供只读

以下是一些有关写入文件的权限模式。 你可以给任何适合你的

file = open('myfile.txt', 'r+')

r+打开一个文件以供读取和写入。 文件指针放置在文件的开头。

file = open('myfile.txt', 'w+')

w+打开用于写入和读取的文件。 如果文件存在,则覆盖现有文件。 如果该文件不存在,请创建一个新文件以进行读写。

file = open('myfile.txt', 'a+')

a+打开一个文件以进行附加和读取。 如果文件存在,则文件指针位于文件的末尾。 该文件以追加模式打开。 如果该文件不存在,它将创建一个用于读取和写入的新文件。

然后,您也需要写入该文件。您可以实现一个简单的解决方法,

file = open('myfile.txt', 'r+')
file.write( "Python \n");
file.close()

为了写入文件对象,您需要为在write(“ w”),append(“ a”),read / write(“ r +”)或append /中打开的文件对象调用fileobj.write()。写模式(“ a +”)。

您需要在函数末尾的某个位置调用:

output_file.write(str(result))  # want character representation

例如:

for i in range(length_o):
    score += (o[i] - e[i])
    result += (score/(sqrt(e[i])))
output_file.write(str(result))

然后,最后,您可能应该关闭文件output_file.close()

(以防万一您多次调用特定模块,最好关闭所有打开的文件对象。通常,这是通过“使用open(filename,mode)as e”完成的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM