I am trying to read a filename that has a period in it, into this simple program..
files like "test" work, while test.txt fail.
I kinda see why. when I type in "test.txt", only "test" appears.
when I use quotes, I get:
IOError: [Errno 2] No such file or directory: "'test.txt'"
is there a simple way I can read file names that have things like extensions?
#!/usr/bin/python
#File Attributes
fn=input("Enter file Name: ")
print (fn) #added so i know why its failing.
f = open(`fn`,'r')
lines = f.read()
print(lines)
f.close()
Using the with...as method as stated in this post:
What's the advantage of using 'with .. as' statement in Python?
seems to resolve the issue.
Your final code in python3 would look like:
#!/usr/bin/python
#File Attributes
fn = input("Enter file Name: ")
with open(fn, 'r') as f:
lines = f.read()
print(lines)
In python2 *input("")** is replaced by raw_input(""):
#!/usr/bin/python
#File Attributes
fn = raw_input("Enter file Name: ")
with open(fn, 'r') as f:
lines = f.read()
print(lines)
I would do it the following way:
from os.path import dirname
lines = sorted([line.strip().split(" ") for line in open(dirname(__file__) + "/test.txt","r")], key=lambda x: x[1], reverse=True)
print [x[0] for x in lines[:3]]
print [x[0] for x in lines[3:]]
You use the input function, this built_in function need a valid python input, so you can try this:
r'test.txt'
But you have to make sure that the test.txt is a valid path. I just try your code, I just change the open function to:
f = open(fn,'r')
and input like this:
r'C:\Users\Leo\Desktop\test.txt'
it works fine.
Related
I am currently trying to search for a specific word in a text file.
I've already wrote my code but it seems that the script is not working correctly.
My code:
main_file = open('myfile.txt','w')
x = 'Hello'
x_main = main_file.write(x)
with open('myfile.txt') as f:
datafile = f.readlines()
for line in datafile:
if 'Hello' in line: #I also tried Hello without the quotes
print("ok")
print(x)
I get only Hello as an output and not ok + Hello.
I hope that someone can help me out with this little problem:)
Thank's for every help and suggestion in advance:)
Your main problem is that you don't close the file after your file after writing to it. Like you have done to open your file with open(file) as file you can do the same in order to read the file. This way you avoid the hastle of writing file.close().
Other than that, your code seems fine.
with open('test.txt','w') as f:
x = 'Hello'
f.write(x)
with open('test.txt') as f:
datafile = f.readlines()
for line in datafile:
if 'Hello' in line: #I also tried Hello without the quotes
print("ok")
print(x)
Try this one
main_file = open('myfile.txt','w')
x = 'Hello'
x_main = main_file.write(x)
main_file.close()
with open('myfile.txt', 'r') as f:
datafile = f.readlines()
for line in datafile:
if 'Hello' in line: #I also tried Hello without the quotes
print("ok")
print(x)
When writing to your file, you never closed the file (file.close()). I would suggest using the open() context manager so you don't have to worry about writing file.close().
string = "Hello"
with open("myfile.txt", "w") as file:
file.write(string)
with open("myfile.txt") as file:
lines = file.readlines()
for line in lines:
if "Hello" in line:
print("OK")
print(string)
For instance here I'm trying to move the contents of file1 into file 2; and this is the code for my attempt which does not work. What's the problem with my code and is there a more efficient method?
file1 = open("textfile.txt", "r")
file2 = open("second textfile.txt","w")
lines = file1.readlines()
for i in range(len(lines)):
file2.write(lines[i]+"\n")
This question is different from other questions of similar type - as it's solution is specific to coding in python.
If you want to copy the content of one file into an other you can do it like this:
firstfile = "textfile.txt"
secondfile = "second textfile.txt"
with open(firstfile, "r") as file:
content = file.read()
file.close()
with open(secondfile, "w") as target:
target.write(content)
target.close()
I am trying to write a program that will open a file and print its contents. I am having some trouble with defining it I suppose? If it is not telling me that "path" is not defined, then it is telling me that "new_dir" is not defined.
Here is the code:
import pathlib
def prog_info():
print("This program will open a file, read and print its contents.")
print("-----------------------------------------------------------")
prog_info()
file_path = new_dir / "numbers.txt"
file_path.parent.mkdir()
file_path.touch()
with path.open("numbers.txt", mode="r", encoding="utf-8") as file:
for line in file:
print(line.strip())
The file is going to have three numbers that will be printed:
22
14
-99
with open("filename or location", 'r') as my_file:
for line in my_file:
print(line)
I hope this helped you.
You don't need mode, and you don't need the import. All you need is the code provided
In environmental variables in system I have defined two variables:
A_home=C:\install\ahome
B_home=C:\install\bhome
following script is written to read information from location of variable A close it, then open location of variable B and write it there, thing is script only works with precise path e.g
C:\install\a\components\xxx\etc\static-data\myfile.xml
C:\install\b\components\xxx\etc\static-data\myfile.xml
problem is, that i need python to read path that is defined in env variable, plus common path like this: %a_home%\a\components\xxx\etc\static-data\myfile.xml`
so far i have this, and i cant move forward .... anyone have any ideas?? this script reads only exact path...
file = open('C:\install\a\components\xxx\etc\static-data\myfile.xml','r')
lines = file.readlines()
file.close()
file = open('C:\install\b\components\xxx\etc\static-data\myfile.xml','w')
for line in lines:
if line!='</generic-entity-list>'+'\n':
file.write(line)
file.write('<entity>XXX1</entity>\n')
file.write('<entity>XXX2</entity>\n')
file.write('</generic-entity-list>\n')
file.close()
Try something like this:
import os
import os.path
home = os.getenv("A_HOME")
filepath = os.path.join(home, "components", "xxx", "etc", "static-data", "GenericEntityList.xml")
with open(filepath, 'r') as f:
for line in f:
print(line)
so finally success Thanks Tom, i was inspired by you ....
here goes
import os
path1 = os.environ['SOME_ENVIRO1']
path2 = os.environ['SOME_ENVIRO2']
file = open(path1 +'\\components\\xxx\etc\\static-data\\GenericEntityList.xml', 'r')
lines = file.readlines()
file.close()
file = open(path2 +'\\components\\xxx\\etc\\static-data\\GenericEntityList.xml', 'w')
for line in lines:
if line!='</generic-entity-list>'+'\n':
file.write(line)
file.write('<entity>ENTITY1</entity>\n')
file.write('<entity>ENTITY2</entity>\n')
file.write('</generic-entity-list>\n')
file.close()
I want to add all lines of content in the file to a list, but the returned list is empty.
def phone_num():
item = []
with open("test.txt", "r") as f:
for i in f.readlines():
item.append(i.strip('\n'))
return item
phone_num()
You can make this method quite concise by taking advantage of list comprehensions:
def phone_num():
with open('test.txt', 'r') as f:
return [line.strip('\n') for line in f]
Also consider using 'rU' as your open mode to enable Universal Newline Support.
Not sure why your result didn't work but it is likely because the file doesn't actually have the contents you want. Try running open("test.txt", "r").read() and ensuring you get output. Since this is a local file you may not be reading from the directory you think you are. Try this:
import os
os.getcwd()
Ensure that this matches the directory where you think your file should is.
This works for me:
def phone_num():
item = []
with open("test.txt", "r") as f:
for i in f:
item.append(i.strip('\n'))
return item
thelist = phone_num()
print (thelist)
If my test.txt file has abc\n efg\n hij\n it stuffs those all into a list