Importing file from path - python-3.x

I am writing a python program that reads from a file 'point.dat' However, when I run the code, I received the error message below.
FileNotFoundError: [Errno 2] No such file or directory: 'points.dat'
May I know what is missing? I tried replacing with the file path but that didn't work as well. any library i need to import in for this to work?
xy=0
xx=0
with open('points.dat') as f:
for line in f:
x,y=[float(p.strip()) for p in line.split(',')]
xy+=x*y
xx+=x*x
k=xy/xx
print('Equation of line y = {:.2f}x'.format(k))
x=input('Enter x coordinate or <ENTER> to end: ')
while x!='':
y=float(input('Enter y coordinate: '))
x=float(x)
if(abs(x*k-y)<1e-2):
print('('+str(x)+',',str(y)+') is on the fitted line')
else:
print('('+str(x)+',', str(y) + ') is not on the fitted line')
x = input('Enter x coordinate or <ENTER> to end: ')
print('End Program')

Can you make sure the extension is correct for the file you are point to? Also have you tried an absolute file path?

Related

Multi line binary file read line by line and convert to char in python

My text file have data as :
01100110011010010111001001110011011101000010000001101100011010010110111001100101
0111001101100101011000110110111101101110011001000010000001101100011010010110111001100101
01110100011010000110100101110010011001000010000001101100011010010110111001100101
so, I need to convert this data file to English by python.
but my programme get some error as :
ValueError: invalid literal for int() with base 2: ''
Please help me to solve this
def bit2strings():
with open('test_doc.txt', 'r' ) as f:
x = (f.read())
for line in x.split(' '):
data = line
if data =='':
print(data)
break
else:
data = f.read(8)
plaintext = chr(int(data, 2))
print(plaintext, end='')
data = f.read(8)
I know that this is not more advance coding part. but how ever lastly write proper programme to solve my problem. I am a beginner to python. so then please give me some comment to do advance this coding part more than this. this is my coding part :
def bit2strings():
with open('test_doc.txt', 'r') as f:
for i in f:
#print(i)
for j in range(len(i)//8):
s = ((i[j * 8:j * 8 + 8]))
#print(s)
get_string = ''.join(chr(int(s, 2)))
print(get_string, end='')
print(end='\n')
if __name__=='__main__':
bit2strings()

Python: read from STDIN unless a file is specified, how is it done?

I'm writing a Python script which expects a regex pattern and a file name and looks for that regex pattern within the file.
By default, the script requires a file to work on.
I want to change the script so by default it would take it's input from STDIN unless a file is specified (-f filename).
My code looks like so:
#!/usr/bin/env python3
# This Python script searches for lines matching regular expression -r (--regex) in file/s -f (--files).
import re
import argparse
#import sys
class colored:
CYAN = '\033[96m'
UNDERLINE = '\033[4m'
END = '\033[0m'
def main(regex, file, underline, color):
pattern = re.compile(regex)
try:
for i, line in enumerate(open(file, encoding="ascii")):
for match in re.finditer(pattern, line):
message = "Pattern {} was found on file: {} in line {}. The line is: ".format(regex, file, i+1)
if args.color and args.underline:
#message = "Pattern {} was found on file: {} in line {}. The line is: ".format(regex, file, i+1)
l = len(line)
print(message + colored.CYAN + line + colored.END, end="")
print(" " ,"^" * l)
break
if args.underline:
l = len(line)
print(message + line, end="")
print(" " ,"^" * l)
break
if args.color:
print(message + colored.CYAN + line + colored.END, end="")
break
if args.machine:
print("{}:{}:{}".format(file, i+1, line), end="")
break
else:
print(message + line, end="")
break
except FileNotFoundError:
print("File not found, please supply")
pass
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Python regex finder', epilog = './python_parser.py --regex [pattern] --files [file]')
requiredNamed = parser.add_argument_group('required named arguments')
requiredNamed.add_argument('-r', '--regex',
help='regex pattern', required=True)
parser.add_argument('-f', '--file',
help='file to search pattern inside')
parser.add_argument('-u', '--underline', action='store_true',
help='underline')
parser.add_argument('-c', '--color', action='store_true',
help='color')
parser.add_argument('-m', '--machine', action='store_true',
help='machine')
args = parser.parse_args()
main(args.regex, args.file, args.underline, args.color)
You can see how a run looks here.
I tried using the answer from this SO question, but getting the following error:
for i, line in enumerate(open(file, encoding="ascii")):
TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper
Edit #1:
This is the file:
Itai
# something
uuu
UuU
# Itai
# this is a test
this is a test without comment
sjhsg763
3989746
# ddd ksjdj #kkl
I get the above error when I supply no file.
Edit#2:
When I change the file argument to that:
parser.add_argument('-f', '--file',
help='file to search pattern inside',
default=sys.stdin,
type=argparse.FileType('r'),
nargs='?'
)
And then run the script like so:
~ echo Itai | ./python_parser.py -r "[a-z]" -m
Traceback (most recent call last):
File "./python_parser.py", line 59, in <module>
main(args.regex, args.file, args.underline, args.color)
File "./python_parser.py", line 16, in main
for i, line in enumerate(open(file, encoding="ascii")):
TypeError: expected str, bytes or os.PathLike object, not NoneType
➜ ~
args.file = tmpfile
which is a file in the same directory where the script runs.
What am I doing wrong?
You wrote this:
def main(regex, file, underline, color):
...
for i, line in enumerate(open(file, encoding="ascii")):
You have some confusion about whether file denotes a filename or an open file descriptor. You want it to be an open file descriptor, so you may pass in sys.stdin. That means main() should not attempt to open(), rather it should rely on the caller to pass in an already open file descriptor.
Pushing the responsibility for calling open() up into main() will let you assign file = sys.stdin by default, and then re-assign the result of open() if it turns out that a filename was specified.

ValueError using split in Python 3.6.5

ValueError: not enough values to unpack (expected 2, got 1)
I am a newb at Python. Trying to run the following script and getting the above error on line 3. Running this in Python 3.6.5. Any ideas?
with open ('namespace.txt', 'r') as f, open ('testfile.txt', 'w') as fo:
for line in f:
t,y =line.split()
fo.write(t + '\n')
print(t)
f.close
fo.close
One of your lines has 1 or 0 fields. If what you want is the first field, you could do this instead:
with open ('namespace.txt', 'r') as f, open ('testfile.txt', 'w') as fo:
for line in f:
t=line.split()
fo.write(t[0] + '\n')
print(t)
f.close
fo.close

I/O operation closed on file in python

I have to write a program that prompts the user to enter six test names and their scores and writes them to a text file named tests.txt. You must use a loop. Each input should be written to its own line in the file. The program should generate a confirmation message when done. When I run my program it works but then I get an error at the end saying:
Traceback (most recent call last):
File "C:/Users/brittmoe09/Desktop/program6_1.py", line 34, in <module>
main()
File "C:/Users/brittmoe09/Desktop/program6_1.py", line 18, in main
test_scores.write(name + '\n')
ValueError: I/O operation on closed file.
I am not sure what I am doing wrong, any help would be appreciated.
Here is my code:
def main():
test_scores = open('tests.txt', 'w')
print('Entering six tests and scores')
for count in range(6):
name = input('Enter a test name')
score = int(input('Enter % score on this test'))
while name != '':
test_scores.write(name + '\n')
test_scores.write(str(score) + '\n')
test_scores.close()
print('File was created successfully')
main()
Here's what I did. Get rid of that 2nd while loop, and move the close file out of the for loop because you are closing the file in the loop which is giving you the error: (some of my variable names are different than yours so look out for that)
test_scores = open('tests.txt','w')#open txt file
print('Entering six tests and scores')
for count in range(6):#for loop to ask the user 6 times
name = input('Enter a test name: ')
testscore = int(input('Enter % score on this test: '))
for count2 in range(1):
test_scores.write(str(name) + '\n')
test_scores.write(str(testscore) + '\n')
test_scores.close()#close the txt file
print('File was created successfully!')
the block while:
while name != '':
...
This is an infinity loop if your "name" != '', so in first loop the file closed and second loop you get an error

Python FileNotFound

I am fairly new to python.
I am trying to make a script that will read sudoku solutions and determent if they are correct or not.
Things I need:
1] Prompt the user to enter a file/file path which includes the sudoku numbers. Its a .txt file of 9 rows and columns. Consist only of numbers.
2] Have some kind of an error handling.
3] Then, if the sudoku is valid, i should create a new text file using the same format as the original input file with the prefix "Correct_"
I have not fully finished the program, but I get this error when I put a false path or file name.
Hello to Sudoku valitator,
Please type in the path to your file and press 'Enter': example.txt #This is a non existing file, to test the Error Exception
'Traceback (most recent call last):
File "C:/Users/FEDROS/Desktop/bs.py", line 9, in <module>
sudoku = open(prompt, 'r').readlines()
FileNotFoundError: [Errno 2] No such file or directory: 'example.txt'
Here is my script:
while True:
try:
prompt = input("\n Hello to Sudoku valitator,"
"\n \n Please type in the path to your file and press 'Enter': ")
break
except (FileNotFoundError, IOError):
print("Wrong file or file path")
sudoku = open(prompt, 'r').readlines()
def check(game):
n = len(game)
if n < (1):
return False
for i in range(0, n):
horizontal = []
vertical = []
for k in range(0, n):
if game[k][i] in vertical:
return ("File checked for errors. Your options are wrong!")
vertical.append(game[k][i])
if game[i][k] in horizontal:
return ("File checked for errors. Your options are wrong!")
horizontal.append(game[i][k])
return ("File checked for errors. Your options are correct!")
print (check(sudoku))
Thanks, any advice or help will be appreciated.
try block should be around open. Not around prompt.
while True:
prompt = input("\n Hello to Sudoku valitator,"
"\n \n Please type in the path to your file and press 'Enter': ")
try:
sudoku = open(prompt, 'r').readlines()
except FileNotFoundError:
print("Wrong file or file path")
else:
break
You can try adding this code before open() function:
import os
pathname = __file__
os.chdir(os.path.dirname(pathname))

Resources