How to copy a text file content and convert it into lines - python

I am trying to make a program that is able to copy a text file and then write out another text file with the same content but changed. For example:
SAS- numbers
PR - 123
SE - 456
TE - 789
The one above is the original text file, but I would like to know how can I make it so it looks like this when my program writes out the copy of the original one:
numbers;123;456;789
This is what I have for now:
openfile = input('Enter the input file: ')
outputfile = input('Enter the output file: ')
output = open(outputfile,'w')
with open(openfile, 'r') as inputfile:
output.write(inputfile.read())
output.close()
Any advice would be really helpful!

Look into my Below code. This might help you.
input_data = ""
with open("input.txt", "r") as f:
input_data = f.readlines()
output_data = ";".join([line.split("-")[1].rstrip("\n").strip() for line in input_data])
with open("output.txt", "w") as f:
f.write(output_data)

Related

How to open an input file, edit it, then save it with a different name with python

I would like to open a text file named file1.txt, count the length, then close it with the name file2.txt.
I very much prefer not importing anything.
file1 = open('file1.txt')
def wordCount(file1):
contents = file1.read()
file1.close()
print(contents)
return len(contents)
print(wordCount(file1))
It comes out as it should but I have no idea where begin the next step of the process.
# Copying then editing files
local_saved = []
with open("file1.txt", "r") as f:
local_saved.append(f.read())
with open("file2.txt", "w+") as f:
text_to_write = local_saved[0]
# Edit text_to_write below.
# Can be deleted (text_to_write = "") or changed in any way as if it were a normal string.
# ...
f.write(text_to_write)
Here it is:
file1 = open('file1.txt')
def wordCount(file1):
contents = file1.read()
file2=open('file2.txt','w')
file2.write(contents)
file2.close()
file1.close()
print(contents)
return len(contents)
print(wordCount(file1))

Search for first occurrence of a string and insert string on line above with python

I usually work in bash so i'm very new to this frightening world of python.
I am attempting to search a file for a string then insert text above the "First occurrence" of that string with empty line between.
The file to be edited would look like this:
Name:
Billy
Thorton
Billy
Thorton
I am trying to insert "Bob" above "Thorton" with the empty lines between like this:
Name:
Billy
Bob
Thorton
Billy
Thorton
This is the Python i have so far.
contents = "Bob"
f = open("file", "w")
contents = "".join(contents)
f.write(contents)
f.close()
This does not search for the string and it replaces the whole file.
A working example in bash would be:
sed -i '0,/Thorton/s//Bob\n\n&/' file
A common way to do so in Python would be to open the file, iterate over it line by line and prepare the results, then write the results to the file.
res = ""
with open("test.txt", "r") as f:
data = f.readlines() # Read the file line by line
found = False
for line in data:
if "Thorton" in line and not found:
res += "Bob\n\n" # Insert Bob if needed
found = True
res += line # Insert the line we just read
with open("test.txt", "w") as f:
f.write(res) # Write the answer in the same file
You could use str.split() to get each item into a list then use list.index() to get the position of "Thorton" to insert from then str.join() to get them back into writable form:
with open('filename.txt', 'r') as infile:
data = infile.read().split()
data.insert(data.index('Thorton'), 'Bob')
with open('filename.txt', 'w') as outfile:
outfile.write('\n\n'.join(data))
you could do
searchedName = "Thorton"
addedName= "Bob"
f = open("file", "w")
content = f.readlines()
index = content.index(searchedName + '\n')
contents = content.insert(index , addedName + '\n')
contents = "".join(contents)
f.write(contents)
f.close()

How to export text to a new file, userinput?

So i wrote a little program in python which allows me to take a .csv file, filter out the lines i need and then export these into a new .txt file.
This worked quite well, so i decided to make it more user friendly by allowing the user to select the file that should be converted by himself through the console (command line).
My problem: The file is imported as a .csv file but not exported as a .txt file which leads to my program overwriting the original file which will be emptied because of a step in my program which allows me to delete the first two lines of the output text.
Does anyone know a solution for this?
Thanks :)
import csv
import sys
userinput = raw_input('List:')
saveFile = open(userinput, 'w')
with open(userinput, 'r') as file:
reader = csv.reader(file)
count = 0
for row in reader:
print(row[2])
saveFile.write(row[2] + ' ""\n')
saveFile.close()
saveFile = open(userinput, 'r')
data_list = saveFile.readlines()
saveFile.close()
del data_list[1:2]
saveFile = open(userinput, 'w')
saveFile.writelines(data_list)
saveFile.close()
Try This:
userinput = raw_input('List:')
f_extns = userinput.split(".")
saveFile = open(f_extns[0]+'.txt', 'w')
I think you probably just want to save the file with a new name, this Extracting extension from filename in Python talks about splitting out the extension so then you can just add your own extension
you would end up with something like
name, ext = os.path.splitext(userinput)
saveFile = open(name + '.txt', 'w')
You probably just need to change the extension of the output file. Here is a solution that sets the output file extension to .txt; if the input file is also .txt then there will be a problem, but for all other extensions of the input file this should work.
import csv
import os
file_name = input('Name of file:')
# https://docs.python.org/3/library/os.path.html#os.path.splitext
# https://stackoverflow.com/questions/541390/extracting-extension-from-filename-in-python
file_name, file_ext_r = os.path.splitext(file_name)
file_ext_w = '.txt'
file_name_r = ''.format(file_name, file_ext_r)
file_name_w = ''.format(file_name, file_ext_w)
print('File to read:', file_name_r)
print('File to write:', file_name_w)
with open(file_name_r, 'r') as fr, open(file_name_w, 'w') as fw:
reader = csv.reader(fr)
for i, row in enumerate(reader):
print(row[2])
if i >= 2:
fw.write(row[2] + ' ""\n')
I also simplified your logic to avoid writting the first 2 lines to the output file; no need to read and write the output file again.
Does this work for you?

Python reading and writing to a .txt file

I need to read the names from the babynames2014.txt file and then create two new files, separating the boys and girls names. The resulting files should be called boynames2014.txt and girlnames.txt. The babynames2014.txt files looks like this:
1 Noah Emma
2 Liam Olivia
3 Mason Sophia
4 Jacob Isabella
and continues until it reaches 100 boy and girls names.
The code I have written so far creates both of the new text files but the boynames2014 contains nothing and the girlnames2014 contains only the name Noah with the number 1 before it like this: 1Noah.
I think that I will need to use readline() and line.split()
somewhere, I'm just not sure where and how to use them correctly. I also need to use a try/except block to handle the exception in case the babynames2014.txt file is not found.
infile = open("babynames2014.txt", "r")
outfile = open("boynames2014.txt", "w")
outfile = open("girlnames2014.txt", "w")
line = infile.readline()
datafield = line.split()
boyname2014 = datafield[0]
girlname2014 = datafield[1]
outfile.write(boyname2014)
outfile.write(girlname2014)
infile.close()
outfile.close()
I have only studied Python for 2-3 months and really appreciate any advice to help me learn more!
I've noticed one thing that is logically not correct i.e., outfile for both boynames2014.txt and girlnames2014.txt
You should've done like this.
infile = open("babynames2014.txt", "r")
outfile_boys = open("boynames2014.txt", "w")
outfile_girls = open("girlnames2014.txt", "w")
Then, you have to read the infile and split by new line for required data as following.
lines = infile.read().split("\n")
Then iterate over the lines as below and split by space(default).
for line in lines:
datafield = line.split()
boyname2014 = datafield[1]
girlname2014 = datafield[2]
outfile_boys.write(boyname2014 + '\n')
outfile_girls.write(girlname2014 + '\n')
I've selected 1 and 2 index for data field because your file contains data like :
1 boy_name girl_name
Splitting by space delivers boy_name to 1st index and girl_name to 2nd index
Then close your files as usual.
infile.close()
outfile_boys.close()
outfile_girls.close()
Hope it helps!
You need to have seperate pointers for output files.
`
infile = open("babynames2014.txt", "r")
outfileboy = open("boynames2014.txt", "w")
outfilegirl = open("girlnames2014.txt", "w")
for line in infile.readlines():
names = line.split(" ")
outfileboy.write(str(names[1]+"\n")
outfilegirl.write(str(names[2]+"\n")
outfileboy.close()
outfilegirl.close()
`
outfile1 = open("boynames2014.txt", "w")
outfile2 = open("girlnames2014.txt", "w")
with open('babynames2014.txt') as infile:
for line in infile:
datafield = line.split()
boyname2014 = datafield[0]
girlname2014 = datafield[1]
outfile1.write(boyname2014)
outfile2.write(girlname2014)
outfile1.close()
outfile2.close()
readline() only reads a single line (as the name might suggest)
so only the first line get read (1 Noah Emma )
To read the all the lines and split them and write them to a file try:
# use two different names for the files
# you had one name `outfile` which was being
# overwritten so tht why boy file was empty
infile = open("babynames2014.txt", "r")
boyfile = open("boynames2014.txt", "w")
girlfile = open("girlnames2014.txt", "w")
with open('babynames2014', 'r') as f:
for l in f.readlines(): # notice readlines instead of readline
_, boy, girl = l.split() # assumes the separator is a space
print(boy, file=boyfile)
print(girl, file=girlfile)
# don't forget to close your file desciptors
boyfile.close()
girlfile.close()
Here you go,
#! /usr/bin/python
import sys
boy_file = str(sys.argv[1])
girl_file = str(sys.argv[2])
all_records = [line.strip() for line in open('babynames2014', 'r')]
f1 = open(boy_file, "w")
f2 = open(girl_file, "w")
for record in all_records:
split_record = record.split(' ')
boy_name = split_record[1]
girl_name = split_record[2]
f1.write(boy_name+"\n")
f2.write(girl_name+"\n")
f1.close()
f2.close()
You have specified the same variable name both the output files. outfile.
infile = open("babynames2014.txt", "r")
outfileb = open("boynames2014.txt", "w")
outfileg = open("girlnames2014.txt", "w")
line = infile.readline()
datafield = line.split()
boyname2014 = datafield[0]
girlname2014 = datafield[1]
outfileb.write(boyname2014)
outfileg.write(girlname2014)
infile.close()
outfileb.close()
outfileg.close()
and you need to loop through the input file in order to get all the names.
You can use ''.join([i for i in s if not i.isdigit()]) to remove the number from the names.
infile = open("babynames2014.txt", "r")
outfileb = open("boynames2014.txt", "w")
outfileg = open("girlnames2014.txt", "w")
tmp = infile.readline()
line=''.join([i for i in tmp if not i.isdigit()])
datafield = line.split()
boyname2014 = datafield[0]
girlname2014 = datafield[1]
outfileb.write(boyname2014)
outfileg.write(girlname2014)
infile.close()
outfileb.close()
outfileg.close()
Want to consider a regex solution?
with open("babynames2014.txt", "r") as f1,open("boynames2014.txt", "w") as boys,open("girlnames2014.txt","w") as girls:
# Note this will not work for name which has speacial charecters like `-,$,etc`
boy_regex = re.compile(r"^\d\s?([a-zA-z0-9]+)\s[a-zA-z0-9]+$",re.MULTILINE)
girl_regex = re.compile(r"^\d\s?[a-zA-z0-9]+\s([a-zA-z0-9]+)$",re.MULTILINE)
boys.write('\n'.join(boy_regex.findall(f1.read())))
girls.write('\n'.join(girl_regex.findall(f1.read())))

Why is it only writing last input to txt?

Output:
Sorry, this was being awfully awkward when I trying to paste my Python code into the code box on this forum post.
Code:
# update three quotes to a file
file_name = "my_quote.txt"
# create a file called my_quote.txt
new_file = open(file_name, 'w')
new_file.close()
def update_file(file_name, quote):
# First open the file
new_file = open(file_name, 'w')
new_file.write("This is an update\n")
new_file.write(quote)
new_file.write("\n\n")
# now close the file
new_file.close()
for index in range(3):
quote = input("Enter your favorite quote: ")
update_file(file_name, quote)
# Now print the contents to the screen
new_file = open(file_name, 'r')
print(new_file.read())
# And finally close the file
new_file.close(
You should be using append instead of write. When you use write, it creates a new file regardless of what was there before. Try new_file = open(file_name, 'a')
Why is it only writing last input to txt?
Everytime you do open(file_name, 'w') it clears the contents of the file and begins to write from the start of the file.
If you would like to append new content to that file do
open(file_name, 'a')
I guess you should use a instead of w to append to file:
new_file = open(file_name, 'a')
And read the docs before asking of course ;)

Categories