Split file based on \r into new rows - python

I have an csv file in my source folder, want to get the output as new line where we have "\r"
Source File
\name\age\gender\r\kiran\29\male\r\rekha\12\female\r\siva\39\male\r
Expected output file
\name\age\gender
\kiran\29\male
\rekha\12\female
\siva\39\male

with open('filename.csv', 'r+') as file:
data = file.readlines()[0].replace(('\\r\\','\n\\'))[:-1]
print(data)

Related

How to modify the contents of an .SVG file with Python?

I have a .svg file with example contents: <svg style="fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.001" /></svg>
I now want to use Python to directly edit the .svg file and change
style="fill:#000000; to my desired color and save it., but I am not sure how to go about this, I have tried a lot of libraries but none do what I
need.
Try this: https://pythonexamples.org/python-replace-string-in-file/
#read input file
fin = open("data.svg", "rt")
#read file contents to string
data = fin.read()
#replace all occurrences of the required string
data = data.replace('style="fill:#000000;', 'style="fill:#FF0000;')
#close the input file
fin.close()
#open the input file in write mode
fin = open("data.svg", "wt")
#overrite the input file with the resulting data
fin.write(data)
#close the file
fin.close()

Empty CSV file when writing lots of data

I am currently conducting a data scraping project with Python 3 and am attempting to write the scraped data to a CSV file. My current process to do it is this:
import csv
outputFile = csv.writer(open('myFilepath', 'w'))
outputFile.writerow(['header1', 'header2'...])
for each in data:
scrapedData = scrap(each)
outputFile.writerow([scrapedData.get('header1', 'header 1 NA'), ...])
Once this script is finished, however, the CSV file is blank. If I just run:
import csv
outputFile = csv.writer(open('myFilepath', 'w'))
outputFile.writerow(['header1', 'header2'...])
a CSV file is produced containing the headers:
header1,header2,..
If I just scrape 1 in data, for example:
outputFile.writerow(['header1', 'header2'...])
scrapedData = scrap(data[0])
outputFile.writerow([scrapedData.get('header1', 'header 1 NA'), ...])
a CSV file will be created including both the headers and the data for data[0]:
header1,header2,..
header1 data for data[0], header1 data for data[0]
Why is this the case?
When you open a file with w, it erases the previous data
From the docs
w: open for writing, truncating the file first
So when you open the file after writing scrape data with w, you just get a blank file and then you write the header on it so you only see the header. Try replacing w with a. So the new call to open the file would look like
outputFile = csv.writer(open('myFilepath', 'a'))
You can fine more information about the modes to open the file here
Ref: How do you append to a file?
Edit after DYZ's comment:
You should also be closing the file after you are done appending. I would suggest using the file like the:
with open('path/to/file', 'a') as file:
outputFile = csv.writer(file)
# Do your work with the file
This way you don't have to worry about remembering to close it. Once the code exists the with block, the file will be closed.
I would use Pandas for this:
import pandas as pd
headers = ['header1', 'header2', ...]
scraped_df = pd.DataFrame(data, columns=headers)
scraped_df.to_csv('filepath.csv')
Here I'm assuming your data object is a list of lists.

In Python read a file content from input and write into output but same content shouldn't append to output

I have a requirement in python to read a file from input where data is fed and write that data to the output file, but before it writes/appends the data into the output file I have to check (compare with existing data in output file):
if the same data is fed once again, it shouldn't write/append to output file (no duplicates)
if the data is different, then only append to output file
At last I resolved it myself. Here is the code:
Input file: ifile.txt
>>> This is my input file data
output file: ofile.txt
>>> hello
process file: process.py
""" Not to append duplicate data to output file"""
existingLines = set(line.strip() for line in open('ofile.txt'))
outfile = open("ofile.txt", "a+")
for content in open('ifile.txt', "r"):
if content not in existingLines: # to void duplicate lines
outfile.write(content+'\n')
existingLines.add(content)
outfile.close()
so now if I run process file again with using the same data of inputfile this data wont be appended to outputfile.
Output will be:
hello
This is my input file data

Parse Text files and save data against some headings in database

I'm working on a python(3.6) project in which I need to parse a text file,
My specific problem is:
My text file has some headings like Examples, Input, Output, Explanations, Notes I need to parse this file and take input & Output headings after Examples headings and write them at end of this file mean after Notes heading and save the file.
Here's I'm trying to get the next line of Examples line:
count = 0
for root, dirs, files in os.walk(os.path.join('description2code_current')):
for file in files:
if file.endswith('description.txt'):
old_name = os.path.join(os.path.abspath(root), file)
print('File Path ````` is: ', old_name)
rf = open(old_name, "r")
lines = rf.readline()
# print(lines)
for line in lines:
line = line.strip()
if line == 'Examples':
print(line)
How can I make that change into my file and then parse it again to save data against these headings into my database?
Help me, please!
Thanks in advance!

Appends text file instead of overwritting it

The context is the following one, I have two text file that I need to edit.
I open the first text file read it line by line and edit it but sometimes when I encounter a specific line in the first text file I need to overwritte content of the the second file.
However, each time I re-open the second text file instead of overwritting its content the below code appends it to the file...
Thanks in advance.
def edit_custom_class(custom_class_path, my_message):
with open(custom_class_path, "r+") as file:
file.seek(0)
for line in file:
if(some_condition):
file.write(mu_message)
def process_file(file_path):
with open(file_path, "r+") as file:
for line in file:
if(some_condition):
edit_custom_class(custom_class_path, my_message)
In my opinion, simultaneously reading and modifying a file is a bad thing to do. Consider using something like this. First read the file, make modifications, and then overwrite the file completely.
def modify(path):
out = []
f = open(path)
for line in f:
if some_condition:
out.append(edited_line) #make sure it has a \n at the end
else:
out.append(original_line)
f.close()
with open(path,'w') as f:
for line in out:
f.write(line)

Categories