Закрыть csv файл python

Закрытие файла CSV в Python

Это похоже или идентично файлу csv, который не закрывает файл, но я не уверен на 100%, почему мое поведение отличается.

def LoadCSV: with open('test.csv', 'r') as csvfile: targetReader = csv.reader(csvfile, delimiter=',') for row in targetReader: . 

Это открывает файл test.csv в том же направлении, что и скрипт. Желаемое поведение заключается в том, когда скрипт сделал то, что он делает с строками в функции, он переименовывает лист для проверки. [Timestamp], чтобы архивировать его и наблюдать за каталогом для нового листа. Позже по коду;

os.rename('test.csv', "test." + time.strftime("%x") ) 

Предоставляет ошибку, что файл нельзя переименовать, поскольку процесс все еще использует его. Как закрыть этот файл, как только закончите? csvfile.close() не вызывает исключения, и если я пройду через свой код в интерактивном режиме, я вижу, что csvfile является «закрытым файловым объектом». Что это такое? Конечно, открытый файл является объектом, но закрытым не является, как заставить мой код забыть, что это даже существует, поэтому я могу сделать IO в файле?

Блок with должен автоматически закрывать файл, когда он выходит из области видимости. Попробуйте переименовать его за пределы блока with

os.rename(‘test.csv’, «test.» + time.strftime(«%x») ) не зависит от определяемого csvfile , не так ли?

Вам не нужен дескриптор файла, чтобы переименовать файл, просто имя файла. os.rename(‘test.csv’. ничего не нужно определять 🙂

Герпес: нет. Qiau: мне может не понадобиться дескриптор, но я все еще не могу закрыть файл, так как он используется из предыдущей части, где был создан дескриптор. Я использую его по имени в конце, потому что дескриптор является частным для функции.

Поскольку код использует имя test.csv в этом блоке каждый раз, когда он выполняется, я должен спросить, запущены ли другие копии кода? т.е. есть проблема с многопоточностью?

Вы уверены, что ваш код — это другой процесс, который не позволяет Windows переименовывать файл? Может быть, существуют ли другие процессы, которые следят за созданием файлов для их анализа (например, антивирус)?

Это недопустимый код Python: def LoadCSV: поэтому, пожалуйста, вставьте фактический код, который вы используете, вместо того, чтобы угадывать, что происходит.

2 ответа

НЕ ДЛЯ ПУНКТОВ.

Код недействителен в любом случае, так как имя вашей функции неверно. Если это не было преднамеренным, лучше отредактируйте его или создайте псевдо-реплику своего кода, а не угадайте, в чем проблема.

Чтобы повторить, проблемы с вашим кодом:

  1. def LoadCSV недействителен. def LoadCSV() есть. Доказательство на следующем скриншоте. Обратите внимание, что отсутствие () показывает маркеры синтаксической ошибки.
  1. Исправляя (1) выше, ваша следующая проблема заключается в использовании csvfile.close() . Если код правильно написан после того, как код из рамки with , файл будет автоматически закрыт. Даже если переименованная часть кода находится внутри функции, она не должна создавать никаких проблем.
  2. Заключительное слово предупреждения — использование строки формата %x приведет к строкам даты, например 08/25/14 , в зависимости от языка. Очевидно, что это неверно, поскольку / недействительно в именах файлов в Windows (попробуйте переименовать файл вручную с этим). Лучше быть очень явным и вместо этого использовать %m%d%y .
Читайте также:  Выполнить php скрипт при открытии страницы

Наконец, см. Текущий код на моем конце. Если ваш код не структурирован так, то могут возникнуть другие ошибки, которые мы не можем догадываться.

После выполнения выполните следующие действия:

import csv import os import time def LoadCSV(): with open("test.csv", "r") as csvfile: targetReader = csv.reader(csvfile, delimiter=",") for row in targetReader: print row new_name = "test.%s.csv" % time.strftime("%m%d%y") print new_name os.rename("test.csv", new_name) LoadCSV() 

Обратите внимание, что на моем конце ничего не наблюдает мой файл. Антивирус включен, и многопоточность явно не включена. Убедитесь, что один из ваших других скриптов одновременно просматривает этот файл для изменений. Лучше, если вместо просмотра файла файл отправляется как аргумент после переименования в эту другую функцию, так как это может быть причиной его «использования». С одной стороны, и это непроверено на моей стороне, возможно, лучше скопировать файл с новым именем, а не переименовать его.

Хорошо, я искал не в том месте, и ваш пункт 2 с «последним словом предупреждения» был кикером, добавление даты было тем, что было на самом деле неправильно. Файл не был заблокирован, он пытался переименовать файл, в котором произошла косая черта в момент, когда Windows разразилась истерикой. Большое спасибо Нанаши

Рад, что это помогло тебе. Я не слишком заинтересован в строках формата, которые можно использовать в strftime самостоятельно, но когда я прочитал документы и показал, что они основаны на локали, у меня возникло предчувствие, что это был либо / либо a . это было частью того, что испортило тебя. С одной стороны, тем не менее, он выбрасывает самые странные из ошибок. В твоем случае выкидывает file being used ошибка. По моему, это file cannot be found ошибка. Забавно, что у IO несколько запутанная трассировка.

Когда вы используете блок with блоком, вам не нужно закрывать файл, он должен быть выпущен за пределы области действия. Если вы хотите, чтобы python «забыл» весь дескриптор файла, вы можете удалить его с помощью del csvfile . Но поскольку вы используете with вами, вы не должны удалять переменную внутри области.

Попробуйте без with рамкой вместо:

csvfile = open('test.csv','r') targetReader = csv.reader(csvfile, delimiter=',') for row in targetReader: . csvfile.close() del targetReader os.rename('test.csv','test.'+time.strftime('%x')) 

Может быть, csv-ридер все равно будет обращаться к файлу, когда вы используете блок with блоком.

Источник

Closing a CSV file in Python

This is similar or identical to csv writer not closing file but I’m not 100% sure why my behaviour is different.

def LoadCSV: with open('test.csv', 'r') as csvfile: targetReader = csv.reader(csvfile, delimiter=',') for row in targetReader: . 

This opens the test.csv file in the same direction as the script. Desired behaviour is for when the script has done what it’s doing to the rows in the function, it renames the sheet to test.[timestamp] to archive it and watches the directory for a new sheet to arrive. Later down the code;

os.rename('test.csv', "test." + time.strftime("%x") ) 

Gives an error that the file can’t be renamed because a process is still using it. How do I close this file once I’m done? csvfile.close() doesn’t raise an exception, and if I step through my code in interactive mode I can see that csvfile is a «closed file object.» What even is that? Surely an open file is an object but a closed one isn’t, how do I make my code forget this even exists so I can then do IO on the file?

Читайте также:  If else true false python

The with block should automatically close the file when it goes out of scope. Try renaming it outside the scope of the with block

os.rename(‘test.csv’, «test.» + time.strftime(«%x») ) doesn’t depend on csvfile being defined does it?

You do not need the file handle to rename the file, just the filename. os.rename(‘test.csv’. doesnt need anything defined 🙂

This is not valid Python code: def LoadCSV: , so please paste your actual code that you are using, rather than having us guess what is going on.

2 Answers 2

NOT FOR POINTS.

Code is not valid anyway, since your function name is wrong. If that was not intentional, better edit it or to produce a pseudo-replica of your code, rather than have us guess what the issue is.

To iterate, the issues with your code:

  1. def LoadCSV is not valid. def LoadCSV() is. Proof in following screenshot. Notice how the lack of () is showing syntax error markers.

enter image description here

  1. Fixing (1) above, your next problem is using csvfile.close() . If the code is properly written, once the code is out of the scope of with , the file is closed automatically. Even if the renaming part of the code is inside the function, it shouldn’t pose any problems.
  2. Final word of warning — using the format string %x will produce date-strings like 08/25/14 , depending on locale. Obviously, this is erroneous, as a / is invalid in filenames in Windows (try renaming a file manually with this). Better to be very explicit and just use %m%d%y instead.

Finally, see the running code on my end. If your code is not structured like this, then other errors we cannot guess might arise.

enter image description here

Result as follows after running:

enter image description here

import csv import os import time def LoadCSV(): with open("test.csv", "r") as csvfile: targetReader = csv.reader(csvfile, delimiter=",") for row in targetReader: print row new_name = "test.%s.csv" % time.strftime("%m%d%y") print new_name os.rename("test.csv", new_name) LoadCSV() 

Note that on my end, there is nothing that watches my file. Antivirus is on, and no multithreading obviously is enabled. Check if one of your other scripts concurrently watches this file for changes. It’s better if instead of watching the file, the file is sent as an argument post-renaming to this other function instead, as this might be the reason why it’s «being used». On the one hand, and this is untested on my side, possibly better to copy the file with a new name rather than rename it.

Читайте также:  Css map content gmod

Источник

Python 2.7.1: How to Open, Edit and Close a CSV file

I’m having trouble opening a file (amount2.csv) making a change, saving it and closing the file. How does one open a file edit, save and close it?

import csv changes = < '1 dozen' : '12' >with open('amount2.csv', 'r') as f: reader = csv.reader(f) print f f.close() 

This may not be cause of error but please see that you open with b flag i.e. ‘rb’ instead of r. The docs for csv.reader say «If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.» It is widely known that it does make a difference on Windows.

2 Answers 2

you are seeing isn’t an error, but the result of your ‘print f’. To instead see the contents of your file, you would do

with open('test.csv', 'rb') as f: reader = csv.reader(f) for row in reader: # row is a list of strings # use string.join to put them together print ', '.join(row) 

To append rows to your file, instead do

changes = [ ['1 dozen','12'], ['1 banana','13'], ['1 dollar','elephant','heffalump'], ] with open('test.csv', 'ab') as f: writer = csv.writer(f) writer.writerows(changes) 

I misunderstood at first, you want to change all entries of ‘1 dozen’ to ’12’ in your csv file. I will say first, this is easier to do without using the csv module, but here is a solution using it.

import csv new_rows = [] # a holder for our modified rows when we make them changes = < # a dictionary of changes to make, find 'key' substitue with 'value' '1 dozen' : '12', # I assume both 'key' and 'value' are strings >with open('test.csv', 'rb') as f: reader = csv.reader(f) # pass the file to our csv reader for row in reader: # iterate over the rows in the file new_row = row # at first, just copy the row for key, value in changes.items(): # iterate over 'changes' dictionary new_row = [ x.replace(key, value) for x in new_row ] # make the substitutions new_rows.append(new_row) # add the modified rows with open('test.csv', 'wb') as f: # Overwrite the old file with the modified rows writer = csv.writer(f) writer.writerows(new_rows) 

If you’re new to programming and python the most trobulesome line is probably

new_row = [ x.replace(key, value) for x in new_row ] 

but this is just a list comprehension that is effectively equivalent to

temp = [] for x in new_row: temp.append( x.replace(key, value) ) new_row = temp 

Источник

Оцените статью