How would I open a file through user input? - python-3.x

This is what I'vre tried so far:
print('''You will have to enter a file name
Once the file name has been entered, the program will then print out your ASCII art''')
file_name = input('Enter file name: ')
with open(file_name) as file_handle:
for line in file_handle:
for x in f:
print(x)

one for loop should be removed from your code as commented and you should print line.
print('''You will have to enter a file name
Once the file name has been entered, the program will then print out your ASCII art''')
file_name = input('Enter file name: ')
with open(file_name) as file_handle:
for line in file_handle:
#for x in f:
print(line)

Related

How to Read ' n ' line from a text file and store it to another text file in python

I have a text file as "file_in.txt".I want read the first three lines from that
file and Write the those three lines read from "file_in.txt" to a new file
called "file_out.txt".
After write it, read "file_out.txt" and Print it's contents
file_in = "file_in.txt"
file_out = "file_out.txt"
data = ""
# read the first 3 lines of file_in.txt
with open(file_in, 'r') as f:
for i in range(3):
data += f.readline()
# write to file_out.txt
with open(file_out, 'w') as f:
f.write(data)
# read the content of file_out.txt
with open(file_out, 'r') as f:
content = f.read()
print(content)

Comparison script diffrent files

i am trying to write a script that compares a bunch of files based on a search word, in this case i searched for 106, then i want the code to match the words from file 1 to the words in file 2 and print a list with the ones that dont match.
For example in file A i have this line
106_LB01_GP61_HAL;LB01;10892;DIGITAL;0;0;0;0;;;Smutsigt tilluftsfilter;;
and in file B i have
"Prefix": "106_LB01_GP61",
those lines match and then i want it to ignore that tag
when the script find lines that dont match etc when a tag in file A cant fint its buddy in file B i want it to write those tags to a file,
for example:
Total unused tags:1
106_LB01_GP61
right now i am stuc at making it read to diffrent files at the same time
#!/usr/bin/env python
#Import os module
import os
# Ask the user to enter string to search
search_path = (".")
file_type = (".wpp")
search_str = input("Enter searchword: ")
resultsFile = "results.csv"
file_name = ("results.csv")
# Append a directory separator if not already present
if not (search_path.endswith("/") or search_path.endswith("\\") ):
search_path = search_path + "/"
# If path does not exist, set search path to current directory
if not os.path.exists(search_path):
search_path ="."
0
# Repeat for each file in the directory
for fname in os.listdir(path=search_path):
# Apply file type filter
if fname.endswith(file_type):
# Open file for reading
fo = open(search_path + fname)
# Read the first line from the file
line = fo.readline()
# Initialize counter for line number
line_no = 1
# Loop until EOF
wf = open(search_path + resultsFile, 'a')
while line != '' :
# Search for string in line
index = line.find(search_str)
if ( index != -1) :
print(fname, "[", line_no, ",", index, "] ", line, sep="")
wf.write(line + " ")
# Read next line
line = fo.readline()
# Increment line counter
line_no += 1
# Close the files
fo.close()
def check_if_string_in_file(file_name, string_to_search):
""" Check if any line in the file contains given string """
# Open the file in read only mode
with open(file_name, 'r') as read_obj:
# Read all lines in the file one by one
for line in read_obj:
# For each line, check if line contains the string
if string_to_search in line:
return True
return False
def check_if_string_in_file(file_name2, string_to_search):
""" Check if any line in the file contains given string """
# Open the file in read only mode
with open(file_name2, 'r') as read_obj:
# Read all lines in the file one by one
for line in read_obj:
# For each line, check if line contains the string
if string_to_search in line:
return True
return False
def search_string_in_file(file_name, string_to_search):
"""Search for the given string in file and return lines containing that string,
along with line numbers"""
line_number = 0
list_of_results = []
# Open the file in read only mode
with open(file_name, 'r') as read_obj:
# Read all lines in the file one by one
for line in read_obj:
# For each line, check if line contains the string
line_number += 1
if string_to_search in line:
# If yes, then add the line number & line as a tuple in the list
list_of_results.append((line_number, line.rstrip()))
# Return list of tuples containing line numbers and lines where string is found
return list_of_results
def search_multiple_strings_in_file(file_name, list_of_strings):
"""Get line from the file along with line numbers, which contains any string from the list"""
line_number = 0
list_of_results = []
# Open the file in read only mode
with open(file_name, 'r') as read_obj:
# Read all lines in the file one by one
for line in read_obj:
line_number += 1
# For each line, check if line contains any string from the list of strings
for string_to_search in list_of_strings:
if string_to_search in line:
# If any string is found in line, then append that line along with line number in list
list_of_results.append((string_to_search, line_number, line.rstrip()))
# Return list of tuples containing matched string, line numbers and lines where string is found
return list_of_results
def main():
print('*** Loading *** ')
matched_lines = search_string_in_file(file_name, search_str)
for elem in matched_lines:
print('Line Number = ', elem[0], ' :: Line = ', elem[1])
# search for given strings in the file 'sample.txt'
matched_lines = search_multiple_strings_in_file(file_name, [search_str])
print('*** Checking if', [search_str], 'exists in a file *** ')
print('Total Matched lines : ', len(matched_lines))
# Check if string 'is' is found in file 'sample.txt'
if check_if_string_in_file(file_name, search_str):
print('Yes, string found in file')
else:
print('String not found in file')
if __name__ == '__main__':
main()

Reading each line from text file

I have a script which reads each line from text file. but somehow it prints all at once. I want to run one line end and run next. here is the code.
f = open('textfile.txt', 'r')
file= f.read()
for x in file:
print(x, file.strip())
comSerialPort.write(x.encode('utf-8'))
Use readlines instead of read
with open('textfile.txt', 'r') as f:
lines = f.readlines()
for line in lines:
print(line)
# do stuff with each line
Use with statement and then iterate lines.
Ex:
with open('textfile.txt', 'r') as infile:
for line in infile:
print(line)
comSerialPort.write(line.strip().encode('utf-8'))
Note: read() reads the entire content of the file.

How to update the contents of a file which consists of Headers in the first line and the values corresponding to it in the corresponding lines

I have a file with below contents:
pid int| name varchar(20)| price float
1 |Giga. |10.99
2. |PowerGiga. |29.99
I want to replace Giga with Mega in the file where the column is Name
and replace price column <15 with 13.99
I have just written the contents given by the user input to a file. Its not stored with any mappings. How do you I replace the name in the file?
Expected:
pid int| name varchar(20)| price float
1 |Mega. |13.99
2. |PowerGiga. |29.99
I have tried this with python as below .
Whats happening is, my entire file content is getting erased
import sys,re
import os
mypath="/Users/rk/Documents/code/PA1/"
db_used="CS457_PA2"
def updateTable():
if os.path.isdir(mypath+db_used):
filepath= mypath+db_used+"/"+filename+".txt"
if not os.path.isfile(filepath): #check if file not exists is true
print("!Failed to insert into table "+ filename +" because it does not exist.")
else :
Column1=List[3]
Column2=List[6]
value1=List[4]
value2=List[7]
newfile=open(filepath, "r")
for w in newfile:
list= w.split('|')
if value1 in list:
print(list)
a=1
print("yes")
newfile=open(filepath, "w")
for a in list:
if value1 in list[0:]:
newfile.write(a.replace(value1,value2))
print("check the file if its updated")
else:
print("nothing")
else :
db_used == " "
print("DB is not selected")
user_says = input().strip()
if "UPDATE" in user_says.upper():
temp=user_says.strip(";")
removespecial=re.sub("\W+", " ", temp) #removes special characters but preserves space
List=removespecial.split(" ")
filename=List[1]
updateTable()
else:
print("Debug")
I tried the below code and it worked for me.
with open(filepath, "rt") as fin:
with open(out, "wt") as fout:
for line in fin:
fout.write(line.replace(value2, value1))
os.remove(filepath)
os.rename(out,filepath)

How do I split a list of first and last names apart?

I'm trying to print only the first names from a .txt list into a new text file.
The .txt list looks like this (each pair of names on its own line, with many more names than shown here):
Smith, James
Doe, John
White, Susan
Here's my current code:
fname = input("Please enter the file name for your list of names: ")
infile = open(fname,"r")
data = infile.read()
outfile = open("student-firstnames.txt", "w")
first = data.split(",")[-1]
print(first, file=outfile)
print("First names have been written to student-firstnames.txt.")
This gives me only the very last first name, but I want an entire list of only first names. What can I do to achieve this?
You could try the following:
first = [i.split(", ")[1] for i in data.split("\n")]
print(first, file=outfile)
This splits the data by newline and then gets the part after the comma, which is the first name.
You can iterate over the file object to process each line of the file one at a time:
with open(fname) as infile:
for line in infile:
...
For example, you could use this to get a list of the first names for each line in the file:
with open(fname) as infile:
first_names = [line.strip('\n').split(', ')[1] for line in infile]
In Python 3 you could do it like this:
fname = input("Please enter the file name for your list of names: ")
with open(fname, "r") as infile, open("student-firstnames.txt", "w") as outfile:
for line in infile:
firstname = line.strip().split(', ')[-1]
print(firstname, file=outfile)
You could try this also to get the names at index 1.
fname = input("Please enter the file name for your list of names: ")
infile = open(fname,"r")
outfile = open("student-firstnames.txt", "w")
x = '\n,'.join([line.split(', ')[1].strip() for line in infile])
outfile.write(x)
outfile.close()
infile.close()
Output:
James
,John
,Susan

Resources