尝试替换文件时为什么访问被拒绝

时间:2019-06-26 18:55:03

标签: python python-3.x csv

我正在尝试通过基本上将名为“ test.csv”的文件复制到“ new.csv”来替换文件,但是即使在同一工作目录中也找不到test.csv。

    def cop(self):
    with open('D:\\johnp\\kivy_venv\\betaapp2\\test.csv') as infile:
        with open('D:\\johnp\\kivy_venv\\betaapp2\\new.csv', 'w') as outfile:
            for line in infile:
            # do things
                outfile.write(line)

    os.replace('D:\\johnp\\kivy_venv\\betaapp2\\new.csv', 'D:\\johnp\\kivy_venv\\betaapp2\\test.csv')




def sign_in(self, text_input):
    self.text_input = text_input
    count = 0
    h = ""
    d = ""
    with open('D:\\johnp\\kivy_venv\\betaapp2\\test.csv', 'r') as fh:
        reader = csv.reader(fh)
        # get the headers out first, which is the first line
        headers = next(reader)

        for line in reader:
            # this will make a dictionary with the header values as
            # keys and the line entries as values
            entry = dict(zip(headers, (l.strip() for l in line)))

            # use key access, it makes the code a bit more readable
            if entry['Name'] == text_input.strip():
                if entry['Position'] == "Vice President":
                    line[8] = float(line[8]) + 3.5
                    self.cop()
                    self.signin()

        else:
            self.noUser()

应该通过运行sign_in并将其复制到new.csv来更新test.csv。然后将test.csv替换为new.csv。

1 个答案:

答案 0 :(得分:0)

它们在同一目录中,但是您尚未指示Python检查以下内容:

import os
base_path = "D:\\johnp\\kivy_venv\\betaapp2\\"

with open(os.path.join(base_path, "test.csv")) as infile:
    with open(os.path.join(base_path, "new.csv"), 'w') as outfile:

没有路径,Python只会在当前工作目录中查找。

相关问题