How can I read individual lines from a CSV file? - python

At the moment I've got this function:
def writer(file_name)
open_file = open(file_name,"r+", newline='')
csv_output = csv.writer(open_file)
csv_output.writerow(student)
open_file.close()
where student is:
"string_1","string_2",int
I'm looking to read through the file first and check if the "string_1" that I'm writing matches any of the "string_1"s already written, but I can't find a built-in function that lets me read each line and store it as a list.

First, you have to open the file for reading, go through the file line by line and return, if "string_1" is found:
def append_student(file_name, student)
with open(file_name, "r") as f:
for line in csv.reader(f):
if line[0] == student[0]:
return
with open(file_name, "a") as f:
csv.writer(f).writerow(student)

Related

Iterator should return strings, not list error with csv.reader

This code shows the error in the title.. Help me out plz.I wrote the following code to write to a csv file reading the input from another file but this shows the error.When i change "r" to "rb" then it shows "iterator should return byte" error.
error->Traceback (most recent call last):
File "C:/Users/abhirav.sati/Downloads/salesdata.py", line 34, in
csv_reader(csvReader,path)
File "C:/Users/abhirav.sati/Downloads/salesdata.py", line 11, in csv_reader
for row in read:
_csv.Error: iterator should return strings, not list (did you open the file in text mode?)
import csv
def csv_reader(fileobj,path):
read=csv.reader(fileobj,delimiter=',')
with open(path, "wt") as csv_file:
write=csv.writer(csv_file, delimiter=',')
i=1
for row in read:
if(i==1):
write.writerow(",".join(row))
i=2
continue
if(row[3]=="Trade"):
continue
else:
if(row[6]==NULL):
r=[row[0],row[0],"A,",row[8],row[9],row[0]]
#r=row[0]+row[0]+"A,"+row[8]+row[9]+row[0]
write.writerow(r)
else:
r=[row[0],row[0],"B,",row[6],row[7],row[0]]
#r=row[0]+row[0]+"A,"+row[8]+row[9]+row[0]
write.writerow(r)
if __name__ == "__main__":
path="sales.csv"
csv_path = "FlowEdge-TRTH-Time_Sales.csv"
f_obj = open(csv_path, "r")
data=csv.reader((line.replace('\0','') for line in f_obj), delimiter=",")
csv_reader(data,path)
Your code is applying csv.reader on another csv.reader object. Look carefully at your __main__ and csv_reader function to make sure you understand why this is the case.
A better solution is to use with open... with multiple files:
with open(path, 'wt') as f1, open('csv_path', 'r') as f2:
write = csv.writer(f1, delimiter=',')
read = csv.reader(f2, delimiter=',')

Append String to each line of .txt file in python?

I want to append some text to every line in my file
Here is my code
filepath = 'hole.txt'
with open(filepath) as fp:
line = fp.readline()
cnt = 1
while line:
#..........
#want to append text "#" in every line by reading line by line
text from .txt file
line = fp.readline()
cnt += 1
You can read the lines and put them in a list. Then you open the same file with write mode and write each line with the string you want to append.
filepath = "hole.txt"
with open(filepath) as fp:
lines = fp.read().splitlines()
with open(filepath, "w") as fp:
for line in lines:
print(line + "#", file=fp)
Assuming you can load the full text in memory, you could open the file, split by row and for each row append the '#'. Then save :-) :
with open(filepath, 'r') as f: # load file
lines = f.read().splitlines() # read lines
with open('new_file.txt', 'w') as f:
f.write('\n'.join([line + '#' for line in lines])) # write lines with '#' appended
I'll assume the file is small enough to keep two copies of it in memory:
filepath = 'hole.txt'
with open(filepath, 'r') as f:
original_lines = f.readlines()
new_lines = [line.strip() + "#\n" for line in original_lines]
with open(filepath, 'w') as f:
f.writelines(new_lines)
First, we open the file and read all lines into a list. Then, a new list is generated by strip()ing the line terminators from each line, adding some additional text and a new line terminator after it.
Then, the last line overwrites the file with the new, modified lines.
does this help?
inputFile = "path-to-input-file/a.txt"
outputFile = "path-to-output-file/b.txt"
stringToAPpend = "#"
with open(inputFile, 'r') as inFile, open(outputFile, 'w') as outFile:
for line in inFile:
outFile.write(stringToAPpend+line)

CSV file to list of lines?

I have a txt file and I want to save each line as a list in a new file with fname as the new file name. But the output is not being saved. What am I missing?
import csv
with open('file.txt', 'rU') as csvfile:
reader = csv.reader(csvfile, delimiter='\t')
i = 1
for line in reader:
fname = line[0] + line[1]
#print fname
with open(fname, 'w') as out:
out.write(line)
i +=1
To do what you want, you need to fix two things, one is to open the output files in "append" mode so their previous contents aren't wiped-out everytime something additional is written to them.
Secondly you need some way to know the raw data from the file for each csv row it reads. This can be difficult when you use an extension like the csv module and don't know the internals (which you shouldn't use anyway).
To work around that in this case, you can pass a custom csvfile argument to the csv.reader that will give you the information needed. Basically a small preprocessor of the data being read. Here's what I mean:
import csv
def pre_reader(file):
"""Generator that remembers last line read."""
for line in file:
pre_reader.lastline = line
yield line
with open('test_gen.csv', 'rU') as csvfile:
reader = csv.reader(pre_reader(csvfile), delimiter='\t')
i = 1
for line in reader:
fname = line[0] + line[1]
#print fname
with open(fname, 'a') as out:
out.write(pre_reader.lastline)
i +=1
Change:
with open(fname, 'w') as out:
out.write(line)
To:
with open(fname, 'a') as out:
out.write(line)
w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
a Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
Better way:
import csv
with open('file.txt', 'rU') as csvfile, open(fname, 'w') as out:
reader = csv.reader(csvfile, delimiter='\t')
i = 1
for line in reader:
fname = line[0] + line[1]
out.write(line)
You cannot write a list so change penultimate line to **out.write(str(line))**
import csv
with open('file.txt', 'rU') as csvfile:
reader = csv.reader(csvfile, delimiter='\t')
i = 1
for line in reader:
fname = line[0] + line[1]
#print fname
with open(fname, 'w') as out:
------> out.write(str(line))
i +=1

Python File I/O: Implementing a function that copy's the content of one text file to an empty text file

Before I begin I would like to state that I am very much a beginner in Python. I am trying to create a function called fcopy() that will take two file names as arguments and copies the content of the first file into the second, when the second file does not exist at the time of the copy. Then get the function to close all files and open the second file for reading. I am using a for statement to read and print the lines in the second file. Here is what I have so far:
def fcopy(file1, file2):
os.chdir('C:/Users/Noah/Documents/myPython')
file1 = str(input('Enter file with text: '))
file2 = str(input('Enter empty file: '))
opened_file= open(file1, 'r')
for lines in file1:
file2.write('file1')
print(lines)
The filenames are passed in as arguments; you don't need to prompt the user to type in the names.
def fcopy(file1, file2):
os.chdir('C:/Users/Noah/Documents/myPython')
open_file_1 = open(file1, 'r')
open_file_2 = open(file2, 'w')
for line in open_file_1:
open_file_2.write(line)
open_file_1.close()
open_file_2.close()
open_file_2 = open(file2, 'r')
for line in open_file_2:
print(line)
open_file_2.close()
If you still want to test if the file2 is non existent at the time of the writing and abort otherwise, you can make it with os.path.isfile in John Gordon code.
def fcopy(file1, file2):
os.chdir('C:/Users/Noah/Documents/myPython')
if(os.path.isfile(file2)):
open_file_1 = open(file1, 'r')
open_file_2 = open(file2, 'w')
for line in open_file_1:
open_file_2.write(line)
open_file_1.close()
open_file_2.close()
open_file_2 = open(file2, 'r')
for line in open_file_2:
print(line)
open_file_2.close()

How to add a value to a specific line in a file in python?

I've seen really complex answers on this website as how to edit a specific line on a file but I was wondering if there was a simple way to do it?
I want to search for a name in a file, and on the line that I find that name on, I want to add an integer to the end of the line (as it is a score for a quiz). Or could you tell me how I can replace the entirety of the line with new data?
I have tried a lot of coding but either no change is made, or all of the data in the file gets deleted.
I tried this....
with open ('File.py', 'r') as class_file:
for number, line in enumerate(class_file):
if name in line:
s=open('File.py', 'r').readlines()
s[number]=str(data)
class_file=open('File.py', 'w')
class_file.writelines(new_score)
class_file.close()
As well as this function....
def replace (file, line_number, add_score):
s=open(file, 'w')
new_data=line[line_number].replace(line, add_score)
s.write(str(new_data))
s.close()
As well as this...
def replace_score(file_name, line_num, text):
new = open(file_name, 'r').readlines()
new[line_num] = text
adding_score= open(file_name, 'w')
adding_score.writelines(new)
adding_score.close()
But I still can't get it to work.
The last code works if I'm trying to replace the first line, but not the others.
You need to get the content of the file. Close the file. Modify the content and rewrite the file with the modified content. Try the following:
def replace_score(file_name, line_num, text):
f = open(file_name, 'r')
contents = f.readlines()
f.close()
contents[line_num] = text+"\n"
f = open(file_name, "w")
contents = "".join(contents)
f.write(contents)
f.close()
replace_score("file_path", 10, "replacing_text")
This is Tim Osadchiy's code:
def replace_score(file_name, line_num, text):
f = open(file_name, 'r')
contents = f.readlines()
f.close()
contents[line_num] = text+"\n"
f = open(file_name, "w")
contents = "".join(contents)
f.write(contents)
f.close()
replace_score("file_path", 10, "replacing_text")
This code does work but just remember that the line_num will always be one above the actual line number (as it is an index). So if you wanted line 9 then enter 8, not 9. Also, do not forget to put .txt at the end of the file path (I would've commented but do not have a high enough reputation)

Categories

Resources