DictReader fieldnames are on the third line not the first [duplicate] - python

This question already has answers here:
Skip first couple of lines while reading lines in Python file
(9 answers)
Closed 3 years ago.
I have somes csvs where the fields names are on the third line.
The two first line are comment and the true csv start at the third line.
What is the best way to use csv.DictReader to start at the third line not the first line ?
Regards

you can call next(f) twice (where f is the file handler) and then pass it to csv.DcitReader() constructor, e.g:
import csv
with open('so.csv') as f:
next(f)
next(f)
dict_rdr = csv.DictReader(f)
for line in dict_rdr:
print(line)

Related

How does not adding a new line erase lines below it [duplicate]

This question already has answers here:
Writelines writes lines without newline, Just fills the file
(8 answers)
Closed 5 months ago.
f= open('elk.in','r')
lines = f.readlines()
for line in lines:
if line.startswith('vkloff'):
p=lines.index(line)+1
#print(lines[p])
break
lines[p] = f'{string}\n'
string=''
with open('elk.in','w') as out:
out.writelines(lines)
out.close()
Here in lines[p] if I remove \n the lines below it get removed. How does it work then?
Taking a few guesses at what your intent here is. You want to open a file, find a line starting with a given prefix, replace it with something else, then write back to the file? There's a few mistakes here if that's the case
You're trying to open a file you already have open. You should close it first.
string is not defined before you use it, assuming this is the full code.
When opening a file using with, you don't need to close it after.
With these in mind you want something like
with open('elk.in','r') as f:
lines = f.readlines()
for idx, line in enumerate(lines):
if line.startswith('vkloff'):
p = idx
break
lines[p] = f'{string}\n'
with open('elk.in','w') as out:
out.writelines(lines)
But really more information is needed about what you're trying to achieve here.

Need to find out how can i write to a .txt file so that the latest results are appended starting from the beginning of the file [duplicate]

This question already has answers here:
Prepend line to beginning of a file
(11 answers)
Closed 1 year ago.
I have build a code that does the following:
#code is supposed to access servers about 20 of them
#server details are in 'CheckFolders.ini'
# retrieve size, file numbers and number of folders information
# put all that in a file CheckFoldersResult.txt
Need to find out how can i write to CheckFoldersResult.txt so that the latest results are appended starting from the beginning of the file instead of appending at end of the existing text.
I'd read the results, insert the lines I want at the top, then overwrite the file like so:
def update_file(filepath, new_lines):
lines = []
with open(filepath, 'r') as f:
lines = f.readlines()
rev_lines = reversed(new_lines)
for line in rev_lines:
lines.insert(0, line)
with open(filepath, 'w') as f:
f.writelines(lines)

Trouble parsing csv file - can't read it 2 times [duplicate]

This question already has answers here:
Why can't I iterate twice over the same iterator? How can I "reset" the iterator or reuse the data?
(5 answers)
Proper way to reset csv.reader for multiple iterations?
(3 answers)
Closed 3 years ago.
Super noob here, so this might be a little embarrasing.
I need to work with a csv file, and found that you can use csv.DictReader to make a list of ordered dicts. So far so good.
I can loop through the list and do stuff, but only one time.
If I want to print the dicts 2 times, it doesn´t work.
import csv
csv_file = open('untitled2.csv', mode='r')
csv_reader = csv.DictReader(csv_file, delimiter = ";")
for rows in csv_reader:
print (rows)
for rows in csv_reader:
print (rows)
This only prints the list of dicts 1 time. I need to go through the list a number of times. but I´m not able to do that.
You need to go to the begining of the file again :
csv_file.seek(0) after the first for.
Don't forget to close it when you're done.
The best way to do it is in a context :
with open('untitiled2.csv', mode='r') as csv_file:
csv_reader = csv.DictReader(csv_file, delimiter=';')
# your for

Write to the last line of a text file? [duplicate]

This question already has answers here:
How do I append to a file?
(13 answers)
Closed 1 year ago.
I am trying to get the program to automatically start at the last line of a text file when I run it and make it write on the last line. My current code is as follows:
with open('textfile.txt', 'a+') as tf
last_line = tf.readlines()[-1]
tf.write(linetext + '\n')`
When I run this, it says that the list index is out of range. How do I get this to automatically skip to the last line of a text file and start writing from there?
Use the a flag while opening the file
with open('path/to/file', 'a') as outfile:
outfile.write("This is the new last line\n")

Python: How to add a line just before my matched pattern [duplicate]

This question already has answers here:
Prepend a line to an existing file in Python
(13 answers)
Closed 9 years ago.
I always do append my new lines just before the pattern </IfModule>.
How can i accomplish this with Python.
Just FYI, my file is not an XML/HTML to use lxml/element tree. IfModule is a part of my .htaccess file
My idea is to reverse the file and search for the pattern , if found append my line just after it. Not so sure how to proceed with.
Read through the file, and when you find the line you're supposed to output before output something first, then output the original line.
with open('.htaccess') as fin, open('.htaccess-new', 'w') as fout:
for line in fin:
if line.strip() == '</IfModule>':
fout.write('some stuff before the line\n')
fout.write(line)
Updating the file inplace:
import fileinput
for line in fileinput.input('.htaccess', inplace=True):
if line.strip() == '</IfModule>':
print 'some stuff before the line'
print line,
Could try replacing </IfModule> with \n</IfModule>
with open('.htaccess', 'r') as input, open('.htaccess-modified', 'w') as output:
content = input.read()
output.write(content.replace("</IfModule>","\n</IfModule>"))

Categories

Resources