Python - Reading from a file, any file - file

I want to make a function that reads from a txt file, thats given by the user on a function. I know how to open a specific file, on python, but I don't know how to make it any file on a function.
For example I want do something like this:
Read_board(irock.txt) --- irock.txt, can be any other fale, it's the argument that the function recieves. Read the line on the file and return it.
This is my final code
def le_tabuleiro(txt):
text = ((open(txt, 'r')).readline())
print text
Thanks everyone.

You need to read from the file object, not its name. Try this:
def read_board(f):
ficheiro = open(f, "r")
line = ficheiro.readline()
return line
Also note that f is a string containing the file name so pass the variable unquoted to open().
One other thing worth mentioning is that you can/should use a with statement to open the file. This will ensure that the file is properly closed once the function returns (or if there is an exception):
def read_board(f):
with open(f, "r") as ficheiro:
return ficheiro.readline()

Related

Dynamic file stream handling in C with freopen

I am trying to write a program that ideally accepts arguments that specify both a source file (to read from) and a destination file (to write to).
The program replaces specified characters in source file, with other specified characters, then writes the output to the destination file.
There are 3 special cases I want to handle, though:
Only a source file to read from is provided.
Desired Behavior: Display the result of replacing the text to the standard output (terminal)
Only a destination file to write to is provided.
Desired Behavior: Read from standard input, replacing desired letters and writing result to destination file name provided.
Neither the source file nor the destination file are provided.
Desired Behavior: Read from the standard in, replace characters, write to standard out.
I believe the way to do this is using freopen(), but I cannot wrap my head around the logic of when the file gets opened or how freopen() 3rd argument (stream) works.
What is the traditional way of handling this problem? Is freopen() even the function I am looking for to do this? Or is there some great lesser known function made for situations like these?
Some pseudo code would be really appreciated.
The third argument is which of the standard file streams you want to replace with a file.
So the logic will be something like:
const char *input_file = NULL;
const char *output_file = NULL;
// parse arguments, setting the above variables to the appropriate arguments if supplied
if (input_file) {
freopen(input_file, "r", stdin);
}
if (output_file) {
freopen(output_file, "w", stdout);
}
Then the rest of the program uses stdin and stdout normally.
The traditional (unixoid) way is to use only stdin and stdout.
If you want to provide an input file, use input redirection:
your_program < input_file
If you want to provide an output file, use output redirection:
your_program > output_file
If you want to provide an input file and an output file, use both ways of redirection:
your_program < input_file > output_file
And you could even add your program to a chain of commands, using pipes:
run_before | your_program | run_after
This gives you a maximum of flexibility.
It is still possible to provide options to your program.

Creating a file using fopen()

I am just creating a basic file handling program.
the code is this:
#include <stdio.h>
int main()
{
FILE *p;
p=fopen("D:\\TENLINES.TXT","r");
if(p==0)
{
printf("Error",);
}
fclose(p);
}
This is giving Error, I cannot create files tried reinstalling the compiler and using different locations and names for files but no success.
I am using Windows 7 and compiler is Dev C++ version 5
Change the mode argument in fopen(const char *filename, const char *mode) from:
p=fopen("D:\\TENLINES.TXT","r");//this will not _create_ a file
if(p==0) // ^
To this:
p=fopen("D:\\TENLINES.TXT","w");//this will create a file for writing.
if(p==NULL) // ^ //If the file already exists, it will write over
//existing data.
If you want to add content to an existing file, you can use "a+" for the open mode.
See fopen() (for more open modes, and additional information about the fopen family of functions)
According to tutorial, fopen returns NULL when error occurs. Therefore, you should check if p equals NULL.
Also, in printf("Error",);, omit the comma after string.
Yes you should open the file in write mode.
Which creates the file . Read mode is only to read content
or else you can use "r+" for both read and write.
You should be able to open the file, but you need to make it first. Make a txt document with the name res.txt. It should be able to write your result into the text document.
<?php
$result = $variable1 . $variable2 "=" .$res ."";
echo $result;
$myfile = fopen("res.txt", "a+") or die("nope");
fwrite($myfile, $result);
fclose($myfile)
?>
fopen()
Syntax:
FILE *fp;
fp=fopen(“data.txt”,”r”);
if(fp!=NULL){
//file operations
}
It is necessary to write FILE in the uppercase. The function fopen() will open a file “data.txt”
in read mode.
The fopen() performs the following important task.
It searches the disk for opening the file.
In case the file exists, it loads the file from the disk into memory. If the file is found with huge contents then it loads the file part by part.
If the file does not exist this function returns a NULL. NULL is a macro defined character in the header file “stdio.h”. This indicates that it is unable to open file. There may be following reasons for failure of fopen() functions.
a.When the file is in protected or hidden mode.
b.The file may be used by another program.
It locates a character pointer, which points the first cha
racter of the file. Whenever a file is
opened the character pointer points to the first character of the file

How do you print the text from a file in Lua?

I would like to be able to print the text from a file. When I use print(io.open(filename,r)), it gives me the file name.
io.open returns a file handle, to read the content, you need io.read:
local f = io.open(filename,r)
print(f:read("*a"))
Learn about IO from The I/O Library.

fopen using append on EXISTING files (malfunction)

Hi all I am relatively new to programming. Currently my code is working "correctly"
What I want to do is open a file for appending and then use couple different other source files to put data on the target file for appending.
The problem is that whenever I use fopen on the file name, it does not open the existing file but rather creates a file with no extension (all the files are in the same directory so should be able to open no problem). This is the code I am using to grab the necessary information for which file to append (error is never generated because it just creates a new file)
FILE *fp_target;
char target[100];
fgets(target, 99, stdin);
if ((fp_target = fopen(target, "a"))==NULL)
{
fprintf(stderr, "the following target file %s can not be appended", target);
exit (0);
}
Actually I tried this test a couple times and when i do this again with the same name used in the first try (lets say I used test.c) the program will open the test.c(no extension rather than the file "test extension (.c)")
can anyone please let me know what I am doing incorrectly?
also, when I fopen a file for reading it will read the file with the extension
Try to remove the newline from the input. By using
target[strlen(target)-1]='\0';
strlen() is used to find the length of the string which is available in string.h header file.
strlen(target)-1 which is used to find the newline location \0 the null character is pasted so the new line is removed.
If you worked with that new line the file is created as test.c?.
In disk we cannot create a file with the already exist name. So the newline is act as one character and the file name is created as like a existing name.
The problem is with your fgets(target, 99, stdin); line. After giving input 'test.c' it takes some garbage values till the end of the array. so every time it creates a new file. Instaed of fgets use scanf to get the input from user.
scanf("%s",target);
if ((fp_target = fopen(target, "a"))==NULL)
{
fprintf(stderr, "the following target file %s can not be appended", target);
exit (0);
}
If you want to use fgets to read the input from the user, after the user input make it NULL.
fgets(target, 99, stdin);
target[strlen(target)-1]='\0';

query regarding writing in a file using c

Assume that the files are .txt
Contents of first file
hello how are you
Contents of second file
I am fine
The desired result is
hello how are you I am fine
Normally what happens is that the original contents are removed and then new contents are added in it.
I want to write in the first file in such a way that its original contents are maintained and the contents of second file are concatenated in it.
Is there any way to do that?
you can append another string in file by opening it in appending mode.
FILE *fp;
fp=fopen("file.txt","a");
here the next string will append after the last pointer of file.For more info link.
Yes, you can open the file with:
fopen("fileName", "a");
This will let you append to the end if the file.
More info is here: http://www.cplusplus.com/reference/cstdio/fopen/
It would help to know how you are trying to write the file. Likely, you are looking for the append option to FOPEN:
http://www.cplusplus.com/reference/cstdio/fopen/
FILE *f = fopen("foo.txt","a");
if (f != NULL) {
/* Use f */
fclose(f);
}

Resources